当 StatusCode 不是 200 时自定义 404 页面不显示

Custom 404 Page not showing when StatusCode is not 200

在我的 web.config 文件中,我启用了自定义错误:

<customErrors mode="On" defaultRedirect="~/Error">
    <error redirect="~/Error/NotFound" statusCode="404" />
</customErrors>

我的 NotFound 操作:

public ActionResult NotFound()
{
    Response.StatusCode = 404;  //no issues when this is not set
    return View();
}

问题: 此配置在本地服务器上运行良好,但当我将其移动到远程服务器时,自定义 404 页面不会显示(显示 IIS 默认 404),除非 NotFound 操作的状态代码设置为 200。

有人能解释一下这是怎么回事吗?

您还想通过将 TrySkipIisCustomErrors 设置为 true 来禁用 IIS 自定义错误。

public ActionResult NotFound()
{
    Response.StatusCode = 404; 
    Response.TrySkipIisCustomErrors = true; <---
    return View();
}