ASP.NET Application_Error Detecting 404’s
For many of you, this is going to be a “Duh!” kind of post. But while working on this today, I found so many people asking this question and so many others giving the wrong answer, I’m compelled to post anyhow.
If you know the answer, then you are welcome to stop reading now. I didn’t write this for you. I wrote this for the hundreds of people who will search for this information and won’t be able to find the answer. The fact of the matter is, that’s why I write most of what I write–so people searching for the information can find it.
So here’s the question:
I’ve set up an Application_Error event handler in my Global.asax file and I have implemented a server transfer for errors. Now I want to set up a specific page to handle 404 errors. How do I detect a 404 error and call the 404-specific page?
The main answer to this question involves retrieving the exception that triggered the event in the first place. To do that, we call Server.GetLastError():
Exception ex = Server.GetLastError();
What we need to do next is determine if the exception is an HttpException or something else. Once we have determined that it is an HttpException we will have access to Http-specific properties and methods that will give us the rest of the information we are looking for. In our case we want to call the GetHttpCode() method, which will return the Http status code and compare it to the number 404.
Our resulting code looks like this:
void Application_Error(object sender, EventArgs e) { Exception ex = Server.GetLastError(); if (ex is HttpException) { if (((HttpException)(ex)).GetHttpCode() == 404) Server.Transfer("~/Error404.aspx"); } // Code that runs when an unhandled error occurs Server.Transfer("~/DefaultError.aspx"); }
Other Related Items:
Rio Grande Games Dominion: SeasideDominion: Seaside is an expansion to both Dominion and Dominion: Intrigue. As such, it does not contain material for a complete game. Specifically, it... Read More >
Waterman Exception Slim Rollerball Pen RedThe pen that breaks away from all expectations and changes the rules.the Exception. With its bold square design the Waterman Exception has powerful pr... Read More >
Maxxis Ignitor Mountain Bike TireMaxxis made this Ignitor Mountain Bike Tire for your 29er. The Ignitors tread pattern fills in to give you low rolling resistance on the straights, an... Read More >










Isn’t it just as easy to do it in web.config?
Doh, seems like my web.config snippet was truncated.
This kb article details what I was thinking of (customError section in web.config): http://support.microsoft.com/kb/306355
That’s a pretty neat trick. Hadn’t seen that before. Thanks
So how to get the wrong requested URL ??
[...] ASP.NET Application_Error – Detecting 404’s [...]
how to get the wrong requested URL ??
See post http://blog.dmbcllc.com/2009/03/31/404-errors-retrieving-the-bad-url/