ASP.NET MVC Routing Shortcoming

Recently I’ve been working with ASP.Net Routing. It has some cool features. I particularly like how the RouteValueDictiontionary works. Give it any type and it will reduce the type to a key/value pair. Awesome! The tokenized routes are another lovely feature, so are the default values.

A pain point I’ve encountered is route evaluation.

For example if you have 10 routes:

  1. mq/s
  2. mq/t
  3. mc/e
  4. mt/t
  5. mt/r
  6. ms/s
  7. tr/r
  8. kl/d
  9. kl/c
  10. kl/x

The routes are evaluated in the order they appear. This is logical. Evaluating a route consists of processing the incoming url and attempting to extract data from it. If no data exists a null is returned to the Routing Engine and the next route is tried. The issue I have is there is no smarts built into the route evaluation. It iterates over the route collection. For example if my route is the last one “kl/x” the first 9 have to be checked before it reaches the correct one. I’m assuming all the routes are relative to the root of the site. Why couldn’t there be a pre-evaluation to eliminate the routes? For example, I’ve requested kl/x. First 9 will be processed before kl/x. Why can’t the routing framework determine that 8, 9, 10 are the closes possible matches? Instead processing 9 routes we process 3.

This gets bigger when custom constraints are added. Say, for each route there is a constraint that looks up a user in the database then the database will be hit 10 times for the same data! Sure you can throw in caching, but that’s not the point.

Wrapping this up, Routing works great for 80 percent of the cases. It’s a good little framework with a few tweaks it could go from good to great.