【发布时间】:2016-03-15 20:49:38
【问题描述】:
我正在尝试抛出 401 HttpException,但应用程序总是返回 500 而不是 401。当我抛出其他 4XX 错误时不会发生这种情况。
public ActionResult Error401()
{
throw new HttpException(401, "Unauthorized");
}
我正在尝试为 500、404、403、400 和 401 创建自定义错误页面。对于除 401 之外的所有错误,我都会获得正确的页面,对于 401,我会进入浏览器 500 错误和 500 自定义错误页面。
<system.web>
<customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="~/CustomErrors/InternalServerError.aspx">
<error statusCode="500" redirect="~/CustomErrors/InternalServerError.aspx" />
<error statusCode="404" redirect="~/CustomErrors/NotFound.aspx" />
<error statusCode="403" redirect="~/CustomErrors/Forbidden.aspx" />
<error statusCode="400" redirect="~/CustomErrors/BadRequest.aspx" />
<error statusCode="401" redirect="~/CustomErrors/Unauthorized.aspx" />
</customErrors>
</system.web>
public class ErrorHandleAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
if (filterContext.HttpContext.IsCustomErrorEnabled == false)
{
return;
}
object exception = filterContext.Exception;
int httpStatusCode = (exception as HttpException).GetHttpCode();
filterContext.HttpContext.Response.Clear();
filterContext.HttpContext.Response.SuppressFormsAuthenticationRedirect = true;
filterContext.HttpContext.Response.TrySkipIisCustomErrors = true;
filterContext.HttpContext.Response.StatusCode = httpStatusCode;
}
}
对于返回正确的 401 自定义页面的其他解决方案有什么想法吗?
谢谢
【问题讨论】:
-
您是否注册了自定义错误属性?
-
是的,它已注册,我得到了 401 旁边的所有自定义错误页面。
标签: c# asp.net asp.net-mvc asp.net-mvc-4 web-config