在ASP.NET中实现404的最佳方法

Ben*_*lls 35 asp.net http-status-code-404

我正在尝试确定在标准ASP.NET Web应用程序中实现404页面的最佳方法.我目前在Global.asax文件中的Application_Error事件中捕获404错误,并重定向到友好的404.aspx页面.问题是请求看到302重定向,然后缺少404页面.有没有办法绕过重定向并使用包含友好错误消息的立即404进行响应?

Googlebot等网络抓取工具是否关心非现有页面的请求是否返回302后跟404?

Zha*_*uid 43

在Global.asax的OnError事件中处理此问题:

protected void Application_Error(object sender, EventArgs e){
  // An error has occured on a .Net page.
  var serverError = Server.GetLastError() as HttpException;

  if (serverError != null){
    if (serverError.GetHttpCode() == 404){
      Server.ClearError();
      Server.Transfer("/Errors/404.aspx");
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

在您的错误页面中,您应该确保正确设置状态代码:

// 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";
Run Code Online (Sandbox Code Playgroud)

你也可以很好地处理这里的各种其他错误代码.

Google通常会遵循302,然后尊重404状态代码 - 因此您需要确保在错误页面上返回该状态代码.

  • 404.htm 页面是否应该是 .aspx 页面,以便您可以在代码隐藏中添加 Response.StatusCode = 404 ? (2认同)

Rob*_*Day 14

您可以使用web.config将404错误发送到自定义页面.

    <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
        <error statusCode="403" redirect="NoAccess.htm" />
        <error statusCode="404" redirect="FileNotFound.htm" />
    </customErrors>
Run Code Online (Sandbox Code Playgroud)

  • 如果你将redirectMode ="ResponseRewrite"添加到<customErrors .. redirectMode ="ResponseRewrite"/>它将重定向.在发送"404 Not Found"状态代码之前,它也不会发送"302 Found"状态代码.你可以随时查看msdn的链接:http://msdn.microsoft.com/en-us/library/h0hfz6fc.aspx (2认同)