ASP.NET MVC redirect to an access denied page using a custom role provider

后端 未结 9 1972
忘了有多久
忘了有多久 2020-12-12 11:20

I\'m creating a custom role provider and I set a Authorize attribute specifying a role in my controller and it\'s working just fine, like this:

[Authorize(Ro         


        
9条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-12 11:58

    I've built on Vic's answer to allow me to have a different Access Denied page for each of the application's areas. Did it by returning a RedirectToRouteResult instead, which instead of redirecting to a URL relative to the root of the application it redirects to the current area's controller and action:

    public class AccessDeniedAuthorizeAttribute : AuthorizeAttribute
    {
        public string AccessDeniedController { get; set; }
        public string AccessDeniedAction { get; set; }
    
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
    
            if (filterContext.HttpContext.User.Identity.IsAuthenticated &&
                filterContext.Result is HttpUnauthorizedResult)
            {
                if (String.IsNullOrWhiteSpace(AccessDeniedController) || String.IsNullOrWhiteSpace(AccessDeniedAction))
                {
                    AccessDeniedController = "Home";
                    AccessDeniedAction = "AccessDenied";
                }
    
                filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { Controller = AccessDeniedController, Action = AccessDeniedAction }));
            }
        }
    }
    

提交回复
热议问题