【问题标题】:ASP.NET MVC Custom Error page (StatusCode 404 throws a 500)ASP.NET MVC 自定义错误页面(StatusCode 404 抛出 500)
【发布时间】:2011-01-23 12:29:37
【问题描述】:

我的 web.config 中设置了 customErrors

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

这在本地运行良好。 404 会引发 404。在共享主机上,它会引发标准服务器 404 页面,除非我专门将 404 设置为指向 /Error/NotFound。没关系。现在它将显示自定义 404 页面,但响应状态代码为 200。所以如果我尝试抛出 Response.StatusCode = 404;在 ErrorController 中的 NotFound 操作中,如下所示:

public class ErrorController : Controller
{
    public ActionResult NotFound()
    {
        Response.StatusCode = 404;
        return View();
    }
}

服务器抛出状态代码 500 Internal Server Error 但我的 GeneralError 页面没有显示,只是一个没有源的空白页面。

我尝试了许多不同的组合,但似乎找不到如何让它显示我的自定义 404 页面以及 404 响应。

有什么想法吗?

【问题讨论】:

  • 允许它在 NotFound 上以 200 OK 响应有什么害处吗?可能是网络抓取或谷歌网站管理员工具的问题。
  • 只是一个想法。在 MVC 应用程序中使用:defaultRedirect="~/Error/GeneralError" 和 redirect="~/Error/NotFound" 会不会更好。 (注意字符串开头的 ~。这将映射到应用程序的基础而不是域的基础......您可能已经知道了。)

标签: asp.net-mvc http-status-code-404


【解决方案1】:

我在这里发现了一些有趣的信息:http://blog.angrypets.com/2008/03/responsetryskip.html

Response.TrySkipIisCustomErrors = true; 

Response.StatusCode = 404; 之后将TrySkipIisCustomErrors 设置为true 可以解决此问题。

【讨论】:

    【解决方案2】:

    不要使用customErrors 元素(除非将mode="On" 用于本地测试)。相反,根据Marco's Better-Than-Unicorns MVC 404 AnswerApplication_EndRequest 方法添加到您的MvcApplication

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-07
      • 2013-07-13
      • 1970-01-01
      • 2013-02-04
      • 1970-01-01
      • 2014-06-27
      • 1970-01-01
      • 2015-03-08
      相关资源
      最近更新 更多