Thursday, November 3, 2011

Configuring MVC Routes in Web.config

ASP.NET MVC is even more configurable than you think!

Routes are registered in the Application Start of an MVC application, but there is no reason that they have to be hard coded in the Global.asax. By simply reading routes out of the Web.config you provide a way to control routing without having to redeploy code, allowing you to enable or disable website functionality on the fly.

I can't take credit for this idea, my implementation is an enhancement of Fredrik Normén's MvcRouteHandler that adds a few things that were missing:

  • Optional Parameters
  • Typed Constraints
  • Data Tokens
  • An MVC3 Library

Download MvcRouteConfig.zip for the project and a sample application.

Example Global.asax

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 
    var routeConfigManager = new RouteManager();
    routeConfigManager.RegisterRoutes(routes);
}

Example Web.config

<configuration>
  <configSections>
    <section name="routeTable" type="MvcRouteConfig.RouteSection" />
  </configSections>
  <routeTable>
    <routes>
      <add name="Default" url="{controller}/{action}/{id}">
        <defaults controller="Home" action="Index" id="Optional" />
        <constraints>
          <add name="custom"
              type="MvcApplication.CustomConstraint, MvcApplication">
            <params value="Hello world!" />
          </add>
        </constraints>
      </add>
    </routes>
  </routeTable>

Thanks Fredrik!

~Tom

Update 2/16/2013 - I have added this source to GitHub and created a NuGet Package.

Shout it

6 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. This is great very informative

    ReplyDelete
  3. I really appreciate this tom.Hole In One Contest Insurance
    I have research this sample code badly starting two days ago. I try youtube but i can't successfully complete it. I will try this and be back to informed you what had happen.

    ReplyDelete
  4. Does this package work with MVC4? I download the full git solution and put in a custom route and it does not work.

    In your previous version you had the RouteManager code but I am assuming that is no longer needed in favor of the ActivatorEx RouteConfigurationActivator.cs file.

    ReplyDelete
    Replies
    1. When I manually register the RouteTable.Routes.RegisterConfigurationBundles(); in my route config.cs file it works but using the RouteConfigurationActivator.cs PostApplicationStartMethod is not registering the routes correctly it seems.

      Delete
    2. Josh, if you are using the NuGet package then you should no longer need the code specified in this blog post. If you do not wish to use the activator then you do not have to, the RegisterConfigurationBundles extension method should work either way.

      Delete

Real Time Web Analytics