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 for the project and a sample application.

Example Global.asax

public static void RegisterRoutes(RouteCollection routes)
    var routeConfigManager = new RouteManager();

Example Web.config

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

Thanks Fredrik!


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

Shout it


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

  2. This is great very informative

  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.

  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.

    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.

    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.

  5. How do I call for Action Result by default which is available in a Area?


Real Time Web Analytics