Provide a custom error page for 401 (failed authorization)

≯℡__Kan透↙ 提交于 2020-01-06 04:46:13

问题


I'm using Windows Authentication. The authentication works fine (the user is loaded with it's roles).

It's when authorization fails (using the Authorize) attribute that I want to provide a custom error page. It seems like the HandleError attribute only gets invoked for thrown exceptions but not for any error status codes (>= 300).

Custom errors section:

<customErrors mode="On" defaultRedirect="~/Error/">
  <error statusCode="404" redirect="~/Error/NotFound/" />
  <error statusCode="401" redirect="~/Error/NotAuthorized/" />
</customErrors>

I got an ErrorController which returns views. But it do never get called.

Do I have to start throwing exceptions in a custom Authorize attribute to be able to handle 401, or is there a better MVC3 specific way?


回答1:


You can override the HandleUnauthorizedRequest in your CustomAuthorize

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
    filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary
                                         {
                                             {"area", ""},
                                             {"controller", "Error"},
                                             {"action", "NotAuthorized"},
                                             {"returnUrl", filterContext.HttpContext.Request.RawUrl}
                                         });
}


来源:https://stackoverflow.com/questions/10993685/provide-a-custom-error-page-for-401-failed-authorization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!