Asp.net MVC Authorize attribute, redirect to custom “no rights” page

前端 未结 5 1461
醉梦人生
醉梦人生 2021-01-31 09:08

Asp.net MVC2 does redirect to login page with response 302 when authenticated user has no rights.

I would like to split into two actions

  1. If us
5条回答
  •  一向
    一向 (楼主)
    2021-01-31 09:24

    You could write custom filter attribute like this:

    public class CustomAuthorizeAttribute : ActionFilterAttribute
        {
            public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                if (filterContext.HttpContext.User.Identity == null || !filterContext.HttpContext.User.Identity.IsAuthenticated)
                {
                    filterContext.Result = new RedirectResult(System.Web.Security.FormsAuthentication.LoginUrl + "?returnUrl=" +
                    filterContext.HttpContext.Server.UrlEncode(filterContext.HttpContext.Request.RawUrl));
                }
    
                //Check user right here
                if (userNotRight)
                {
                    filterContext.HttpContext.Response.StatusCode = 302;
                    filterContext.Result = new HttpUnauthorizedResult();
                }
            }
        }
    

    And use it in controller:

    [CustomAuthorize]
    public class HomeController : Controller
    {
    
    }
    

提交回复
热议问题