Sunday, November 23, 2008

ASP.NET MVC Routing Using XML Custom Configuration Settings

In ASP.NET MVC application, you need to add some routing code in the Application_Start of the Global.asax file to define your routing criteria. These lines of code take a shape of configuration settings for the MVC application and I was thinking if we can transfer these configurations line of codes to be XML settings in the web.config file. My target is to make the routing configuration in the web.config file as following:

As you can see, the later configurations define the Ignore and Routing lists of the MVC application. In the "Ignore" list, you define the URL criteria to be ignored by the MVC routing. In the "Map" list, you specify a list of the routes including the route name, controller and action. You can also define any optional parameter mappings for your actions.

To do that, I have to create a custom configuration section: MvcRouteConfigurationSectin. The section has a IgnoreCollection - inherited from ConfigurationElementCollection class - of IgnoreItem and another RoutingCollection of RouteItem.

The solution will also add an extension method for RouteCollection object so that you will be able to map the configuration section in the web.config directly to your RouteTable.

To use the project, you just need to include the MvcXmlRouting.dll in your MVC web project. Then you add the following line inside the configSection Tag in web.config:

You then define the ignore and the routing configurations for your web application as defined earlier in the web.config. Finally, you will need to edit the RegisterRoutes method in the Global.asax file to add a couple of lines as following:

Now all your routing configuration will go to the web.config file. No need to edit the Global file anymore. However, changing the routes in the web.config still need to reset your IIS as the routing is registered in Application_Start.

Download: Binary | Source Code

The project is implemented using ASP.NET MVC Beta 1 and Visual Studio 2008. It's not guaranteed that this project or the related assemblies will properly work in earlier or newer version of ASP.NET MVC Framework.

kick it on
DZone - Vote Up!

Ping Back Links:


Mohamed Meligy said...

You may also be interested in the other way that exits :)

The benefit of the other way it that this is actual code. You can go any advanced level (say support ignore routes or something for simplicity) without having to do code in the configuration section that supports it.

Alexander P said...

Great post! I've got a request: could you please re-share those sources and binaries? In case you do so, please choose upload server different from :) Thank you very much in advance.
--regards, Alex