【问题标题】:How do you correctly handle 404 errors in ASP.NET?如何正确处理 ASP.NET 中的 404 错误?
【发布时间】:2010-10-11 05:24:03
【问题描述】:

您可以在 web.config 中添加此代码来处理 404 错误:

<customErrors mode="Off" defaultRedirect="ErrorPage.aspx">
  <error statusCode="404" redirect="/Site-Map"/>
</customErrors>

你可以通过这个 URL http://www.fundraising.com.au/thisisnotapage 看到这个效果很好

但是,根据这个网站http://gsitecrawler.com/tools/Server-Status.aspx,这个不存在的页面的响应代码是 200,而不是 404。

虽然此页面 http://www.nuenergy.com.au/thisisnotapage 确实在 http://gsitecrawler.com/tools/Server-Status.aspx 处显示 404 并重定向到另一个页面。

你如何在ASP.NET中实现后面的? 我需要响应为 404 并显示另一个页面。

【问题讨论】:

    标签: asp.net response


    【解决方案1】:

    custom errors section employs the HttpHandler 拦截您没有页面的事实,然后 redirects the response 以便服务器返回 Site-Map 而不是可用资源,因此 200 状态是正确的,因为它好像请求是首先是Site-Map

    您最终希望提供两种版本的Site-Map,一种是实际请求 (200),另一种是自定义错误响应 (404)。我将创建另一个版本的Site-Map 页面OnError-Site-Map,扩展页面类以继承它的功能,然后overriding the http response code 以便它提供您想要的404 状态,但仅适用于该扩展版本。然后,您将其放在 web.config 的自定义错误部分中。

    【讨论】:

      【解决方案2】:

      要让您的页面返回 404 状态,请将以下代码添加到您的 Page_Load 事件中:

      Protected Sub Page_Load1(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
      
          Response.Status = "404 Not Found"
      
      End Sub
      

      【讨论】:

        猜你喜欢
        • 2010-10-11
        • 2019-09-11
        • 2011-04-12
        • 2020-10-31
        • 1970-01-01
        • 2010-10-05
        • 1970-01-01
        • 2011-11-20
        相关资源
        最近更新 更多