Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to implement a 404 in ASP.NET

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?

Does a web crawler such as Googlebot care if the request for a non existing page returns a 302 followed by a 404?

like image 981
Ben Mills Avatar asked Mar 20 '09 17:03

Ben Mills


People also ask

What is 404 error asp net?

Best web development and SEO practices dictate that any webpage which does not exist, return an HTTP response code of 404, or Not Found. Basically, this response code means that the URL that you're requesting does not exist.

How does web API handle 404 error?

A simple solution is to check for the HTTP status code 404 in the response. If found, you can redirect the control to a page that exists. The following code snippet illustrates how you can write the necessary code in the Configure method of the Startup class to redirect to the home page if a 404 error has occurred.

How does global ASAX handle 404 error?

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.


1 Answers

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.

like image 119
Zhaph - Ben Duguid Avatar answered Sep 23 '22 18:09

Zhaph - Ben Duguid