为401提供自定义错误页面(授权失败) [英] Provide a custom error page for 401 (failed authorization)
问题描述
我正在使用Windows身份验证.身份验证正常(向用户加载了角色).
I'm using Windows Authentication. The authentication works fine (the user is loaded with it's roles).
我要提供自定义错误页面的授权失败(使用 Authorize
)属性.似乎 HandleError
属性仅被引发的异常调用,而没有任何错误状态代码(> = 300
)被调用.
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
).
自定义错误部分:
<customErrors mode="On" defaultRedirect="~/Error/">
<error statusCode="404" redirect="~/Error/NotFound/" />
<error statusCode="401" redirect="~/Error/NotAuthorized/" />
</customErrors>
我有一个 ErrorController
返回视图.但是它永远不会被调用.
I got an ErrorController
which returns views. But it do never get called.
我是否必须开始在自定义的 Authorize
属性中引发异常才能处理401,还是有一种更好的MVC3特定方式?
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?
推荐答案
您可以在 CustomAuthorize
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary
{
{"area", ""},
{"controller", "Error"},
{"action", "NotAuthorized"},
{"returnUrl", filterContext.HttpContext.Request.RawUrl}
});
}
这篇关于为401提供自定义错误页面(授权失败)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!