Debugging Routes

Previously Scott Hanselman pointed out that in CodeCampServer we are using a tiny wrapper around MvcRouteHandler in order to catch all exceptions and provide the route information along with the error message.  I called this (for lack of a better name) BetterMvcRouteHandler.  That’s right, Better!

Scott took this a mile further and created a nice route debugging table that you can use while debugging.  You can download this route debugger on Phil’s blog (with source).

To enable the route table debugger, you have to add this line to your global.asax:

RouteDebug.RouteDebugger.DebugRoutes(RouteTable.Routes);

I think it would be better to be able to add ?routedebug to the end of ANY url and have this happen automatically.  To accomplish this I created an HttpModule.  It looks at each request for the ?routedebug querystring key and, if found, calls the line above.  I ran into a hiccup, though… once you set the route handler to the debug one, all future requests use it as well (even without the url parameter). 

Good ‘ol Phil released the source for this route debugger, so I added a method to revert the routes back to their original values if the query parameter doesn’t exist.

Here is the RouteDebugModule:

Route_debug_module

(remember:  this code would NOT be appropriate for production use, both for the awkward setting of route handlers on every request and the fact that you don’t want your users to be able to see your route information.)

And the RevertRouteHandlers method (in Phil’s RouteDebugger.cs):

Revert_routes

The _oldRouteHandlers is just a static dictionary that hangs on to the route before swapping with the debug one.

I added the HttpModule to my web.config, and now I can do this:

Route-debug-in-action

…and also flip back to the regular request without recompiling.

I’m thinking they should call this BettererRouteHandler instead of RouteDebugHandler, who’s with me?

#1 Haacked avatar
Haacked
3.17.2008
1:22 PM

Very cool!You should do a check to make sure the app is running in DEBUG mode (I honestly forget how, but I bet I could look it up in 5 min ;). That way if you accidentally deploy this module, it won't work in prod.