ASP.NET MVC – Why doesn’t my area route registration work?

Also known as watch the precedence order of your registrations!

We have recently begun switching our MVC project to leverage the Areas feature in MVC.  This is a big benefit and allows us to organize our application functionally as opposed to by file type.  As an example it allows us to put everything about updating an individual in the Individual area (controller, view, static assets, etc) instead of having them in a folder by file type.

One problem we recently encountered was that it appeared the routing for our areas was not working correctly all of the time.  In one case the route: /individual/profile/update/4C009C91-1DED-4E36-B19C-5D00A90E31E9 was working (where area = individual, controller = profile, action = update, {GUID} = id).  While another area route was not: /subscription/renew (where area = subscription, renew = controller, index = action, id = null).

I verified that the area was being correctly registered and that all of the necessary code was in the global.asax, but I just couldn’t figure out why it was not able to find the controller action.  It was returning 404 for the request.

So, I took the debugging one level deeper to try and peer inside MVC routing.  I enabled RouteDebugger 2.0 (by Phil Haack) on the server side and looked at the routes being evaluated:

RouteRegistrations

As you can see the route matched two patterns ({controller}/{action}/{id} and Subscription/{controller}/{action}/{id}).  Unfortunately the one I wanted it to match was second!  To fix this I just needed to register them in the opposite order so that my area registrations would have preference.  I moved AreaRegistration.RegisterAllAreas() above my routes.MapRoute() method invocations and my area controller began working.

I learned a couple of valuable lessons  from this adventure:

  1. RouteDebugger is your friend!  Kudos to Phil Haack for a great utility that provides insight into your MVC server-side routing.
  2. Areas should be registered before the default MVC route ({controller}/{action}/{id}).  <–Important safety tip!

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.