404 redirects in code with ASP.NET
I have had problems doing proper 404 redirects in ASP.NET ever since I started to care about proper 404 pages. I do not have any trouble if the page does not exist. But say for example that I require a query string on some page and for some reason, I do not get a query string. Then I guess it’s proper to give a 404 error. Today I decided to give it another try and finally, I think I have found the solution thanks to two great tips on the amazing Stackoverflow.com.
The first one is that if you want to throw a 404 error you can just do.
throw new HttpException(404, “Article not found”);
As simple as that. In almost all other articles I read about this people are talking about doing Response. Status = 404 and stuff like that. The problem with that is that the page will continue to execute and you most likely get some kind of error if something vital is missing.
The next thing I learned where that you could do like this.
Notice the “redirect mode” property. It will cause asp.net to not change the URL but do a “Server.Transfer” like redirect to the error page but keep the URL that throws the error.