Omair Shakeel

Saturday, March 13, 2010

Defining ASP.NET MVC routes in web.config

ASP.NET MVC has a very declarative way of defining your routes in the code itself, especially in the Application_Start method of Global.asax.

Since MVC does not have any support of defining them in the configuration file I thought of writing my own configuration section in the web.config and a class that does the simple tasks of mapping the routes and adding simple route constraints. Changes to routes will not require recompilation of your code.

So spending an hour on this I coughed up some code that you can download.

On the other hand, defining routes in code does indeed give the advantage of doing advanced stuff like defining more specific/complex constraints, custom route constraints, ignore routes etc. But if you do not have such requirements and have simple routes you could use this code.

Using the code add the following section under the
of your web.config and add reference to MyWebMvc.dll:

<
section name="mvcroutesgroup" type="MyWebMvc.MvcRoutesConfiguration, MyWebMvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=nullallowLocation="true" allowDefinition="Everywhere"/>

Then declare your routes such as:

<mvcroutesgroup>
  <mvcroutes>



    <route name="Product" url="Product/{action}/{id}">
      <controller name="Product" />
      <constraints>
         <constraint key="id" value="\d+" />
      </constraints>
    </route>
  <route name="Default" url="{controller}/{action}/{id}">      <controller name="Home" action="Index" id="" />
    </route>
  </mvcroutes>
</mvcroutesgroup>

Add the following code where you register your routes in the Global.asax file:

MvcRoutes.Initialize(routes);

What I can add later here is the support for:


  • Namespaces (to be used in Areas)
  • Ignore routes
You can download the code from here.

0 Comments:

Post a Comment

<< Home