Skip to content
darrencauthon edited this page Apr 13, 2011 · 1 revision

Routing

Routing in MVC Turbine works in a very similar manner as routing in standard ASP.Net MVC applications. You still use the ASP.Net RouteCollection, you still use the ASP.Net helper methods like MapRoute and IgnoreRoute, and the order in which you add your routes matters.

So what's the difference? MVC Turbine makes routing extensible with its IRouteRegistrator interface:

public interface IRouteRegistrator {
    void Register(RouteCollection routes);
}

Whenever your ASP.Net MVC application starts up, MVC Turbine will find all implementations of IRouteRegistrator, instantiate them through your IoC container, and pass the RouteCollection to each.

This gives you the ability to create modules that can inject their own routes into your application, so long as they are included in the bin of your MVC application.

Example Use:

MvcTurbine.GoogleSiteMap is a dll that contains everything necessary to create a Google-compatible sitemap to your MVC application. Included in this dll is an IRouteRegistrator that maps the "/sitemap.xml" route to its own special controller that generates the XML. By adding a reference to MvcTurbine.GoogleSiteMap, this sitemap IRouteRegistrator will be swept into your application, effectively adding a /sitemap.xml to your application with no additional work.

But What About the Order of the Routes?

MVC Turbine does not allow you to control the order in which the IRouteRegistrators are instantiated and used. In fact, the order may change from one build to another. The only control you have on order is inside a single implementation of IRouteRegistrator (which, in many cases, might be enough).

So how do you manage routes that conflict when you can't control the order in which they run? That's easy:

Don't write routes that conflict.

The easiest way to do this is to use an often-forgotten feature of ASP.Net routing: The RouteConstraint. Attach a route constraint to your routes that prevent them from matching in cases where they should not.

The best example of the need for this is the "/{controller}/{action}/{id}" route. Without a route constraint, it will match against any URL request that is 0-3 segments long, even if it doesn't match a controller. That's a pretty wide-reaching route that forces most MVC developers to add this route last. However, if you attach a route constraint that only matches against controllers, then you don't have to worry about where this route is added.