2016-09-15 93 views
0

我的MVC网页当前使用Session变量进行身份验证。我想尝试一下,所以我可以使用一个自定义的AuthorizeAttribute,这样我就可以用[CustomAuth]来装饰控制器。您如何重定向到自定义AuthorizeAttribute的动作结果

当前RedirectToRouteResult带我到“此页面无法显示”页面。代码打到第一个RedirectToRouteResult。

它不相同的,如果我使用RedirectResult

,我怎么把它引导到登录页面我有吗?

这是我customAuth

public class CustomAuth : AuthorizeAttribute 
{ 
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) 
    { 
     if (filterContext.RequestContext.HttpContext.Session["isAuth"] != null) 
     { 
      if (!(bool)filterContext.RequestContext.HttpContext.Session["isAuth"]) 
      { 

       filterContext.Result = new RedirectToRouteResult(new 
        RouteValueDictionary(new { controller = "Base", action = "Login" })); 
      } 
     } 
     else 
     { 
      filterContext.Result = new RedirectToRouteResult(new 
       RouteValueDictionary(new { controller = "Base", action = "Login" })); 
     } 
    } 
} 

编辑---

我想使用而不必把这个每一个动作每一个控制器控制器和动作[customAuth]

if (Session["isAuth"] != null) 
     { 
      if (!(bool)Session["isAuth"]) 
      { 
       Session.Clear(); 
       return RedirectToAction("Login", "Base"); 
      } 
     } 
     else return RedirectToAction("Login", "Base"); 

有没有办法做到这一点与匿名身份验证?

+0

的路径是什么,以你的登录页面? – Luke

+0

基地/登录,如果我把_Login的行动,我需要http:// localhost:/ Base/_Login与资源无法找到页面,这是预期的原因没有_Login。但是,如果我把基地/登录它不重定向它只显示无法显示页面。 – user1314413

+0

您能够成功导航到/ base/login吗?另外,你的控制器实际上是否叫做'BaseController'? – Luke

回答

0

下面是我如何使用从HandleErrorAttribute派生的属性进行操作。

只需将filterContent.Result分配给新的ViewResult以设置目标。如果你需要它们,别忘了其他属性。

public class HandleUnauthorizedAttribute : HandleErrorAttribute 
{ 
    public override void OnException(ExceptionContext filterContext) 
    { 
     base.OnException(filterContext); 

     if (filterContext.Exception.GetType() != typeof (SecurityException)) return; 

     var controllerName = (string) filterContext.RouteData.Values["controller"]; 
     var actionName = (string) filterContext.RouteData.Values["action"]; 
     var model = new HandleErrorInfo(filterContext.Exception, controllerName, actionName); 

     filterContext.Result = new ViewResult 
     { 
      ViewName = "Unauthorized", 
      ViewData = new ViewDataDictionary<HandleErrorInfo>(model), 
      TempData = filterContext.Controller.TempData 
     }; 
     filterContext.ExceptionHandled = true; 
     filterContext.HttpContext.Response.Clear(); 
     filterContext.HttpContext.Response.StatusCode = 403; 
     filterContext.HttpContext.Response.TrySkipIisCustomErrors = true; 
    } 
} 

的我刚刚注册它在FilterConfig.cs

public class FilterConfig 
{ 
    public static void RegisterGlobalFilters(GlobalFilterCollection filters) 
    { 
     filters.Add(new HandleUnauthorizedAttribute()); 
    } 
} 
+0

你的控制器是用[HandleUnauthorizedAttribute]装饰还是抛出那个自定义异常? – user1314413

+0

你使用的是什么版本的mvc?我将mvc 5的注册码添加到答案中。这将在每个请求上放置过滤器。但如果你想,你可以放在控制器或动作上。 – Fran

+0

我认为你很混淆认证和授权。如果您所做的只是检查用户是否已通过身份验证,则可以在web.config中配置该用户,并将未经身份验证的用户发送到登录URL。 – Fran

相关问题