为 HTTP 状态代码提供页面

Serving Up Pages for HTTP Status Codes

我正在尝试为 ASP.NET 4.5.2 Web 窗体项目设置 500 和 404 页。当不存在的页面是 .ASPX 页面时,我得到了 404。 - 我编写了代码以提供自定义 NotFound.aspx 页面作为响应。

当我使用 Web.config 为不存在的 HTML 页面提供 404.html 页面时,我的问题就出现了。我的 404.html 页面位于根文件夹中。如果我使用根文件夹中不存在的 HTML 页面进行测试,404.html 会正确呈现。但是,如果我在不存在的子文件夹中使用不存在的 HTML 页面对其进行测试,则会提供 404.html,但 CSS/JS 路径不再正确?这就像将 CSS/JS 路径视为与我在测试中指定的不存在的子文件夹相关?

Global.asax.cs:

void Application_Error(object sender, EventArgs e)
{
    Exception ex = Server.GetLastError();

    if (ex != null && ex is HttpUnhandledException)
    {
        Server.ClearError();
        Server.Transfer("~/Error.aspx", true);
    }

    if (ex != null)
    { 
        var httpException = ex as HttpException; 
        if (httpException.GetHttpCode() == 404)
        {
            Server.ClearError();
            Server.Transfer("~/NotFound.aspx", true); 
        }
    }
}

Web.config:

<httpErrors errorMode="Custom" existingResponse="Replace">
    <remove statusCode="404" />
    <error statusCode="404" path="404.html" responseMode="File" />
</httpErrors>

对 CSS/JS 路径使用绝对 URLs。例如,在您的 404.html 中(bootstrap 和 jquery 只是示例):

<link href="/Content/bootstrap.min.css" rel="stylesheet" />
<script src="/Scripts/jquery-3.0.0.min.js"></script>
<script src="/Scripts/bootstrap.min.js"></script>

另一种设置是设置 responseMode="Redirect":

<httpErrors errorMode="Custom" existingResponse="Replace">
  <remove statusCode="404" />
  <error statusCode="404" path="/Errors/404.html" responseMode="Redirect" />
</httpErrors>

在此示例中,404.html 位于文件夹 Errors 中,URL 可以是相对的:

<link href="../Content/bootstrap.min.css" rel="stylesheet" />
<script src="../Scripts/jquery-3.0.0.min.js"></script>
<script src="../Scripts/bootstrap.min.js"></script>

这会起作用,因为重定向 URL 不再与您请求的 URL 相关。

我是这样解决的:

<httpErrors errorMode="Custom" existingResponse="Replace">
    <remove statusCode="404" />
    <error statusCode="404" path="http://localhost/myproject/404.html"
        responseMode="File" />
</httpErrors>

要点在于,此版本的路径必须是绝对路径才能正常工作。所以我的下一步是尝试以编程方式设置路径,以便在调试模式下它会转到我的本地,而在发布模式下会转到生产 URL。我不想弄乱 Web.config 转换文件。

如果有人有任何进一步的信息,请随意。