2016-07-26 16 views
0

ユーザーがセッション変数として保存されるようにカスタム認証が設定されています。彼らはアカウント/ログインプロセスを経るたら私はこのようなセッションにユーザーとしてサードパーティのAPIから返された詳細情報を格納します。MVCのカスタム認証

Session["User"] = new UserViewModel(result); 

私は、ユーザーを確認したいが、私が持っているので、すべてのコントローラのアクションの前に存在していますその中に次のチェックでBaseControllerを作っ:ユーザが存在しない場合は、ページのログインにリダイレクトするよう

protected override void OnActionExecuting(ActionExecutingContext filterContext) 
{ 
    if (Session["User"] != null) 
    base.OnActionExecuting(filterContext); 
    else 
    filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary(new { action = "LogIn", controller = "Account" })); 

各コントローラ、その後BaseControllerから継承されます。私はAccountControllerのBaseControllerを継承していないので、チェックとリダイレクトの無限ループに陥ることはありませんが、特定のページにログインをチェックしないようにしたいのです。 [AllowAnonymous]と同じ方法で例外ルールを記述しますか?あなたのように、これらの方法でフィルタを使用することができ

+0

コントローラ上で、その後

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)] public class ActionCheckAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) { string controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.ToLower().Trim(); string actionName = filterContext.ActionDescriptor.ActionName.ToLower().Trim(); // this is just a sample.. you can implement any logic you want if (!actionName.StartsWith("your method name") && !controllerName.StartsWith("your controller name")) { var session1 = HttpContext.Current.User.Identity.Name; HttpContext ctx = HttpContext.Current; //Redirects user to login screen if session has timed out if (session1 == null) { base.OnActionExecuting(filterContext); filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Account", action = "LogOff" })); } } } } 

は、などの属性を置きますカスタムのAuthorize属性を作成し、このチェックを実行するコントローラにのみ適用してみましょう。 – Alex

+0

ActionFiltersの代わりにAuthorize属性をオーバーライドする –

答えて

0

として
[ActionCheck] 
public class MyController : Controller 
{ 
    public ActionResult Index() 
    { 
     return View(); 
    } 
} 

または特定のアクションメソッド上:

[ActionCheck] 
public Actionresult SomeMethod() 
{ 
    return View(); 
}