Custom 404 Message with Bad URL Parameters

Have you ever built a site that contains a page that accepts a parameter like https://mycommecesite/productdetails.aspx?pid=10? What happens when a user tries to enter an invalid product id? It would be nice if you could show them a nice custom error page with very minimal coding. Turns out you can do this with as little as 2 lines of code. The first step is to configure a 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.

The next step is to throw the proper exception and let ASP.Net handle the request for you and display a nice friendly message to your user. All that needs to be done is to throw HttpException like:

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

The ASP.NET run-time will catch the exception and will redirect to the custom 404 page and now your site behaves well and consistent!