【问题标题】:HTTP errors not consistent using customErrors mode="On"使用 customErrors mode="On" 的 HTTP 错误不一致
【发布时间】:2018-12-19 22:06:02
【问题描述】:

我正在使用类似的 URL http://localhost:52200/<http://localhost:52200/<xyz 测试自定义错误处理。不知何故,我得到了不一致的结果。

Web.Config:

<!--MVC pipeline-->
<customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="~/Error.aspx">
    <error statusCode="404" redirect="~/404.aspx" />
    <error statusCode="500" redirect="~/500.aspx" />
</customErrors>

<!--IIS pipeline-->
<httpErrors errorMode="Custom">
  <remove statusCode="404"/>
  <error statusCode="404" path="404.html" responseMode="File"/>
  <remove statusCode="500"/>
  <error statusCode="500" path="500.html" responseMode="File"/>
</httpErrors>

customErrors mode="Off" 时,都返回相同的HTTP 400 Bad Request

但是,当customErrors mode="On" 时,只有http://localhost:52200/&lt; 返回HTTP 400 Bad Request,然后重定向到Error.aspx

现在,http://localhost:52200/&lt;xyz 返回HTTP 500 Internal Server Error 并转到:

当我删除ResponseRewrite 时,两者都返回HTTP 302 Found 并重定向到Error.aspx。我不想要这个,因为我丢失了 http 错误代码。

我做错了什么?

【问题讨论】:

    标签: asp.net-mvc iis http-error custom-errors


    【解决方案1】:

    解决了!由于我不知道的原因,MVC 管道需要 defaultRedirect 指向 .html 文件:

    <customErrors mode="On" redirectMode="ResponseRewrite" defaultRedirect="~/Error.html">
    

    Global.asax.cs 中添加Response.ContentType = "text/html"; 可以避免错误页面呈现为文本的已知问题:

    protected void Application_Error()
    {
        var exception = Server.GetLastError();
        if (exception is HttpException httpException)
        {
            Response.ContentType = "text/html";
            Response.StatusCode = httpException != null ? httpException.GetHttpCode() : (int)HttpStatusCode.InternalServerError;
        }
    }
    

    另外,Response.StatusCode 确保正确的 HTTP 错误代码到达客户端(例如 400、503 等)而不是 200。

    有了web.configglobal.asax.cs 中的这两个块并且没有对IIS 进行任何更改,http://localhost:52200/&lt;http://localhost:52200/&lt;a 现在都返回HTTP 400 Bad Request 并按预期显示Error.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多