如何正确处理 ASP.NET 中的 404 错误?
在 web.config 中,您可以添加此代码来处理 404 错误:
<customErrors mode="Off" defaultRedirect="ErrorPage.aspx">
<error statusCode="404" redirect="/Site-Map"/>
</customErrors>
正如您通过此 URL http://www.fundraise.com.au/thisisnotapage
但是,根据该网站http://gsitecrawler.com/tools/Server-Status.aspx 这个不存在的页面的响应代码是 200,而不是 404
。 nuenergy.com.au/thisisnotapage" rel="nofollow">http://www.nuenergy.com.au/thisisnotapage 确实在 http://gsitecrawler.com/tools/Server-Status.aspx 并重定向到另一个页面。
在 ASP.NET 中如何实现后者? 我需要响应为 404 并显示另一个页面。
In the web.config you can add this code to handle 404 errors:
<customErrors mode="Off" defaultRedirect="ErrorPage.aspx">
<error statusCode="404" redirect="/Site-Map"/>
</customErrors>
And this works well as you can see by this URL http://www.fundraising.com.au/thisisnotapage
However, according to this website http://gsitecrawler.com/tools/Server-Status.aspx the response code for this non-existent page is 200, not a 404.
Whilst this page http://www.nuenergy.com.au/thisisnotapage does show a 404 at http://gsitecrawler.com/tools/Server-Status.aspx and redirects to another page.
How do you achieve the later in ASP.NET?
I need the response to be a 404 and for another page to show up.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
自定义错误部分使用 HttpHandler 拦截您没有页面的事实,然后重定向响应,以便服务器返回
Site-Map
而不是是可用资源,因此 200 状态是正确的,因为该请求首先是针对Site-Map
的。您最终希望提供两个版本的
Site-Map
,一种是实际请求 (200),另一种是自定义错误响应 (404)。我将创建Site-Map
页面的另一个版本,OnError-Site-Map
,扩展页面类以继承其功能,然后 覆盖 http 响应代码,以便它提供您想要的 404 状态,但对于仅该扩展版本。然后,您可以将其放在 web.config 的自定义错误部分中。The custom errors section employs the HttpHandler to intercept the fact you don't have a page and then redirects the response so that the server returns
Site-Map
instead which is an available resource so the 200 status is correct since its as though the request was forSite-Map
in the first place.You ultimately want to serve two versions of
Site-Map
, one when it is the actual request (200) but also one when it is the custom error response (404). I would create another version of theSite-Map
page,OnError-Site-Map
, extending the pages class to inherit it's features but then overriding the http response code so that it delivers the 404 status you want but for that extended version only. You then put that in the custom errors section in the web.config instead.为了让您的页面返回 404 状态,请将以下代码添加到您的 Page_Load 事件中:
For your page to return a 404 status, add the following code to your Page_Load event: