Troubleshooting ASP.NET MVC Routing

One thing I absolutely love about the ASP.NET MVC framework is that there isn't too much "magic". Magic can be nice if you are able to adhere to a framework's "Golden Path", but as soon as some customization becomes necessary you find that the magic can get in the way (DataContractSerializer anyone?).

One of the places in the ASP.NET MVC framework (and now part of .NET SP1) where magic is happening is routing. Routing takes a url, looks for the best fit from the pre-defined list of routes, breaks it up into parameters and feeds the whole thing to a handler. Pretty sweet, but if you have done something wrong it'll be tough to tell since all that is happening behind the scenes.

I've created a personal checklist to follow when I start to have routing troubles, if you have any additional steps you've found useful please post them in the comments and I will try to keep this checklist up to date. This article covers troubleshooting routes when using the ASP.NET MVC framework, however some of the steps mentioned will be applicable no matter how you are using routing.

1. Verify your controllers and actions.

I'm a contract first developer. I'll typically define my routes and views before I develop the controllers to use them. It's happened more than once that I started testing before I had written the method in my controller that I'm trying to access.

2. Look for duplicate routes.

This may not be as obvious as it seems. It's easy to create duplicate routes that read different but are hard for the routing system to distinguish. Remember that every parameter in your route is basically an empty slot where some data can be, so if you have 2 routes with the same number of slots in the same locations, they will be indistinguishable by the routing system.

3. Make sure your most specific routes are first.

Routes are tested against the URL in the order that they were added. If there is a less specific route that your URL can "fit" into before the one you actually wanted to execute, the routing system will choose that one and never get to your more specific route.

These 3 steps have helped me to successfully solve every routing issue I've come across so far, but if you have any other tips, I'd love to hear them.

4 Comments

Comments have been disabled for this content.