The best way of handling the route exceptions in MVC

What is route exception?

When a URL of the incoming request doesn’t match any of the mapped routes, in this case you get a HTTP 404 error. Let users receive the default 404 ASP.NET page is not a good practice. And we are going to handle it in a better way.

The typical solution is to enforce .net framework to use custom error pages, here’s how to register ad hoc routes in asp.net,

    <customErrors defaultRedirect="~/error" mode="Remote">
      <error statusCode="404" redirect="~/error/NotFound"></error>
    </customErrors>

The trick is working just fine. There is no reason to question it from a functional perspective. But what is the problem?
Let’s take a close look at it. Imagine that when we are requesting a invalid URL, the application issues an HTTP 302 code and tells the caller it is temporarily moved to another location. Then the application redirect to the error page.

For human, you probably will not even notice it. But for Search engines, it leads the search engines to conclude the content is not missing at all. And an error page is catalogued as regular content.

The better way of dealing with the missing content is to register a catch all route, to capture any URLs sent to the application that haven’t been mapped to the existing routes. Here is the sample,

routes.MapRoute(

   "Errors", 

   "{*anything}",  

   new { controller = "Error", action = "Missing" } 

);

Of course, you will need an Error controller to handle the request and present a nice view to the users.

public class ErrorController : Controller
{
  HttpContext.Response.StatusCode = 404;
  HttpContext.Response.TrySkipIisCustomErrors = true;

  //log error
  return View();
}

TrySkipIisCustomErrors property of the response object is a new property to address a feature of the IIS 7 integrated pipeline.

Advertisement

One thought on “The best way of handling the route exceptions in MVC

  1. Thanks for a nice article. Though, how do you handle ignorant URLs? For example, I have routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”); and afterwards I include route for 404. The first rule doesn’t work, my *.axd files return 404 error.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s