MVC5抛出401的HttpException返回500

时间:2015-12-10 09:32:42

标签: c# asp.net asp.net-mvc asp.net-mvc-4 web-config

我试图抛出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的正确自定义页面?

由于

1 个答案:

答案 0 :(得分:-1)

你应该尝试这样做

public ActionResult Error401()
{
   return new HttpStatusCodeResult(HttpStatusCode.Forbidden, "Forbidden");
}

然后你不需要每次都抛出异常,因为它更贵。