Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In ASP.NET how to identify/process 404 exceptions?

I need to handle 404 exceptions differently than all other types of them. What is the best way to identify those 404 exceptions (distinguish them from other exceptions)?

The problem is that there is no a special exception class for 404 errors, I get regular System.Web.HttpException with Message = "File does not exist."

Should I just use exception's message for it or is there a better way?

Thank you.

like image 534
Alex Kovshovik Avatar asked Feb 11 '11 03:02

Alex Kovshovik


People also ask

What is the error message for 404 in 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 exceptions are handled in ASP NET application?

Exception class. An exception is thrown from an area of code where a problem has occurred. The exception is passed up the call stack to a place where the application provides code to handle the exception. If the application does not handle the exception, the browser is forced to display the error details.

Why is 404 File or directory not found?

The following are some common causes of this error message: The requested file has been renamed. The requested file has been moved to another location and/or deleted. The requested file is temporarily unavailable due to maintenance, upgrades, or other unknown causes.


2 Answers

You can try to cast the exception as an HttpException, and then use the GetHttpCode method to check whether it is a 404 or not.

For example:

Exception ex = Server.GetLastError();

HttpException httpEx = ex as HttpException;

if (httpEx != null && httpEx.GetHttpCode() == 404)
{
   //do what you want for 404 errors
}
like image 106
patmortech Avatar answered Sep 19 '22 05:09

patmortech


I'd suggest that you configure your application to redirect 404 errors to a specific page, such as ~/FourOhFour.aspx. In this page you can inspect the aspxerrorpath querystring parameter, which will report the page the user was attempting to visit. From here you can do all sorts of interesting things, from logging the 404, to emailing yourself a message, to trying to determine the correct URL and auto-redirecting the user to that.

To configure your web application to redirect the user to a custom page in the face of a 404, add the following markup to web.config in the <system.web> section:

<customErrors mode="On" defaultRedirect="~/GeneralError.aspx">
    <error statusCode="404" redirect="~/FourOhFour.aspx" />
</customErrors>

For more information, see:

  • <customErrors> element documentation
like image 26
Scott Mitchell Avatar answered Sep 23 '22 05:09

Scott Mitchell