.NET Tip of The Day
Learn one new .NET trick every day
Быстрое пополнение счета телефона      Login or Join

How to respond with code 404 (Not Found) in ASP.NET

Suppose you configured custom 404 page in web.config file in the customErrors section. So whenever user requests non-existent aspx page, ASP.NET run-time returns well formatted message to the user.

Also you have a page that shows articles from a database according to article ID passed in the url (for example: article.aspx?id=345). But if user passes article ID that doesn't exists the page must return code 404 (Not Found) and show the custom 404 page like in the previous situation.

Fortunately you don't need to parse the customErrors section to get name of the custom 404 page. Just throw HttpException:

    throw new HttpException(404, "Article not found");

ASP.NET run-time will catch the exception and will redirect to the custom 404.

8/26/2008
RSS .NET Tip of The Day
Subscribe to receive one tip from the .NET Tips and Tricks Community per day.
Previous Tips of The Day
The best of the .NET Tips & Tricks Community.
.NET Practitioners .NET Tips & Tricks Community
Every .NET practitioner has a trick up in their sleeve. This is the place to share it with other .NET people.
Submit a Tip
Discovered a new trick? Share it with others.
My Tips
Manage tips you authored.