Redirect Unauthorized Page Access in MVC to Custom View

后端 未结 5 1727
温柔的废话
温柔的废话 2020-12-23 16:36

I have an MVC website in which access is based on various Roles. Once a user logs into the system they can see navigation to the pages for which they are authorized. However

5条回答
  •  滥情空心
    2020-12-23 16:43

    With following change it is working

    public class CustomAuthorize : AuthorizeAttribute
    {
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            //filterContext.Result = new HttpUnauthorizedResult(); // Try this but i'm not sure
              filterContext.Result = new RedirectResult("~/Home/Unauthorized");
        }
    
        public override void OnAuthorization(AuthorizationContext filterContext)
        {
            if (this.AuthorizeCore(filterContext.HttpContext))
            {
                base.OnAuthorization(filterContext);
            }
            else
            {
                this.HandleUnauthorizedRequest(filterContext);
            }
        }
    
    }
    

    And then applying on Controller or Action as below:

    [CustomAuthorize(Roles = "Admin")]
    

    With above approach I need to revisit all the controller/actions and change the Authorized attribute! Also some testing will be needed.

    I am still not sure why Web.Config route not working as same has been explained in MVC Documentation. May be something has changed in MVC 4!

提交回复
热议问题