ASP.Net MVC Framework 2 - Define Routes in Web.config

Something I like with ASP.Net MVC Framework Preview 2 is the RouteValueDictionary used by the Route class’s Defaults, Constraints and DataTokens property, before they use an anonymous type. Because the properties are now a specific type it’s much easier to define the routes in web.config. Before it was quite easy but some reflection was needed. I have now created a ConfigSection and a helper method to easily register routes which can be defined in the web.config for the Preview 2 version of the ASP.Net MVC Framework. I decided to use the following XML structure to define routes in web.config:

<routeTable>
  <routes>
  
<
add
name="Microsoft"
url="{controller}/{action}/{id}"
routeHandlerType="MyMvcRouteHandler">
<
defaults action="Index" id=""/> <constraints id="..."/> <dataTokens/>
</
add>
<
add name="Default" url="Default.aspx"> <defaults controller="Home" action="Index" id=""/> </add>
</
routes> </routeTable>

In my solution I also decided to make sure the “name” attribute of a route <add> is required and used as a key. The two other attributes of the route <add> are “url” and “routeHandlerType”, used to specify the Url and the type of a IRouteHandler to use (by default if it's empty the MvcRouteHandler will be used). I decided to use three child elements to the <add> element, <defaults>, <constraints> and <dataTokens>. Each attribute added to those elements will be added to the property of the Route class with the same name as the element and as a key, value dictionary of type RouteValueDictionary. To make it easy to register and read the routeTable out from the web.config, I created a helper class “RouteTableManager”. By calling its static method “RegisterRoute” from Application_Start in global.asax, the routes were registered.

RouteTableManager.RegisterRoutes(RouteTable.Routes);

Or

RouteTableManager.RegisterRoutes();

The last method will use the RouteTable class internally.

By creating a custom MvcRouteModule and override the Init method, the routes can be automatically registered without using global.asax.

public class MyUrlRouteingModule : UrlRoutingModule
{
    protected override void Init(HttpApplication application)
    {
        RouteTableManager.RegisterRoutes();
        base.Init(application);
    }
}

You can download the whole source code from here..

Note: The code will only read the routes from the Configuration file, you can’t use it to modify or add new routes. The idea is only to define the routes in a config file instead of adding them manually in the global.asax’s Application_Start event. I also put the source code into the Model directory of the ASP.Net MVC Project, it should be separated into an own assembly, but I was lazy ;)

2 Comments

Comments have been disabled for this content.