Type safe route registration in ASP.NET MVC

October 18, 2009 17:25

A few days ago my workmate Ian made a point that there should be a nice way to implement type safe route registration in ASP.NET MVC.

Type safe! Can anyone read these words without experiencing a tug of excitement, without being swayed by the view of departed bugs and newly arrived refactorings on controllers and actions - refactorings that don't break your app?

Indeed, type safe is possible. Here's how we register our routes now:

routes.MapRoute(
    "viewProduct",                                                        
    "{locale}/{product}/view/{mode}/",                                 
    new { controller = "Product", action = "Display", mode = "full" }  
);
 
and here's a type safe way:

routes.MapRoute(
    "{locale}/{product}/view/{mode}/")
     .On<ProductController>(x => x.Display("full"));

More...