问题
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