Custom file not found (404) error pages can help to create a more rewarding user experience for your site visitors. Links become outdated and there is nothing more frustrating for a user than to have found a link to exactly what they are looking for and to come across the infamous “file not found” screen.
Fortunately, ASP.NET MVC makes it relatively easy to implement something more meaningful for your visitors. Using a wildcard routing rule you can ensure that all completely malformed requests are transferred to a specific controller.
In the above example, any requests that do not match any of our other routing rules will be forwarded to the Http404 action on the Error controller.
At this point, there are a few things worth pointing out.
For one thing, the routing must be the last route mapped. This is because of how ASP.NET MVC prioritizes routes. It essentially goes in order of the declarations looking for a match and stops the moment it finds one. Since our route only contains a wildcard, if it had been listed before any other routing rules those other rules would never get executed.
Another thing worth pointing out involves similar routing concerns. Take for example our error route and the default route that every ASP.NET MVC application starts with.
While the routes are defined in the correct order you still might be surprised what happens when the user requests the following URL:
When the framework encounters the second routing rule:
It sees that http://example.com/foo matches. In complete ignorance of our other route, the framework immediately starts looking for a controller named foo.
So for our error route to get executed the URL has to completely malformed, or in other words, the URL cannot match any of our previously defined routes. The following are URLs that would execute the error route in our example:
While limited in its application, this technique for handling malformed URLs is useful. In our example controller, you have access to the requested URL and could potentially parse that to provide recommendations to help a lost visitor find what they are looking for. Taking this one step further you may want to read my article on Handling Unknown Controller Actions In ASP.NET MVC