Search code examples
asp.net-mvcasp.net-membershiproleprovider

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


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(Roles="SuperAdmin")]
public class SuperAdminController : Controller
...

But when an user doens't have access to this controller, he's redirected to login page. How can I redirect him to a "AcessDenied.aspx" page?


Solution

  • [AccessDeniedAuthorize(Roles="SuperAdmin")]
    public class SuperAdminController : Controller
    

    AccessDeniedAuthorizeAttribute.cs:

    public class AccessDeniedAuthorizeAttribute : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            base.OnAuthorization(filterContext);
    
            if(filterContext.Result is HttpUnauthorizedResult)
            {
                filterContext.Result = new RedirectResult("~/AcessDenied.aspx");
            }
        }
    }