Best way to implement a 404 in ASP.NET

前端 未结 9 704
甜味超标
甜味超标 2020-11-27 16:26

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 Glob

相关标签:
9条回答
  • 2020-11-27 17:12

    You can configure IIS itself to return specific pages in response to any type of http error (404 included).

    0 讨论(0)
  • 2020-11-27 17:17

    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 (serverError != null){
        if (serverError.GetHttpCode() == 404){
          Server.ClearError();
          Server.Transfer("/Errors/404.aspx");
        }
      }
    }
    

    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";
    

    You can also handle the various other error codes in here quite nicely.

    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.

    0 讨论(0)
  • 2020-11-27 17:18

    Do you use this anywhere?

     Response.Status="404 Page Not Found"
    
    0 讨论(0)
提交回复
热议问题