最好的方法在ASP.NET中实现404
我试图确定一个标准的ASP.NET Web应用程序实现404页的最佳途径。我现在赶上Application_Error事件404错误在Global.asax文件重定向到一个友好404.aspx页面。问题是,在请求看到一个302重定向后跟一个缺失的404页。有没有办法绕过重定向并立即404包含友好的错误消息反应?
I'm trying to determine the best way to implement a 404 page in a standard ASP.NET web application. I currently catch 404 errors in the Application_Error event in the Global.asax file and redirect to a friendly 404.aspx page. The problem is that the request sees a 302 redirect followed by a 404 page missing. Is there a way to bypass the redirect and respond with an immediate 404 containing the friendly error message?
难道一个网络爬虫如Googlebot的护理如果一个不存在的页面请求返回一个302后跟一个404?
Does a web crawler such as Googlebot care if the request for a non existing page returns a 302 followed by a 404?
在您的Global.asax的OnError事件处理这个问题:
Handle this in your Global.asax's OnError event:
protected void Application_Error(object sender, EventArgs e){
// An error has occured on a .Net page.
var serverError = Server.GetLastError() as HttpException;
if (null != serverError){
int errorCode = serverError.GetHttpCode();
if (404 == errorCode){
Server.ClearError();
Server.Transfer("/Errors/404.aspx");
}
}
}
在你的错误页面,你应该确保你设置的状态code正确的:
In you error page, you should ensure that you're setting the status code correctly:
// If you're running under IIS 7 in Integrated mode set use this line to override
// IIS errors:
Response.TrySkipIisCustomErrors = true;
// Set status code and message; you could also use the HttpStatusCode enum:
// System.Net.HttpStatusCode.NotFound
Response.StatusCode = 404;
Response.StatusDescription = "Page not found";
您也可以处理各种其他错误codeS这里相当不错。
You can also handle the various other error codes in here quite nicely.
谷歌将一般遵循302,再兑现404状态code - 所以你需要确保你返回你的错误页面
Google will generally follow the 302, and then honour the 404 status code - so you need to make sure that you return that on your error page.