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

45 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
  5. How do I call for Action Result by default which is available in a Area?

    ReplyDelete
  6. I just found this blog and have high hopes for it to continue. Keep up the great work, its hard to find good ones. I have added to my favorites. Thank You. freelance web designer

    ReplyDelete
  7. Great article Lot's of information to Read...Great Man Keep Posting and update to People..Thanks Website Designing Company

    ReplyDelete
  8. I really appreciate this wonderful post that you have provided for us. I assure this would be beneficial for most of the people. Website Designing Company

    ReplyDelete
  9. The expression "Word Wide Web" was first presented in that joint proposition. Webdesign

    ReplyDelete
  10. I really like all of the articles, I truly loved, I'd like more info relating to this, simply because it's very good., Many thanks with regard to discussing. kmspico

    ReplyDelete
  11. Took me time to read all the comments, but I really enjoyed the article. It proved to be Very helpful to me and I am sure to all the commenters here! It’s always nice when you can not only be informed, but also entertained! Website redesign

    ReplyDelete
  12. Great post I would like to thank you for the efforts you have made in writing this interesting and knowledgeable article. Howard Stern net worth

    ReplyDelete
  13. Wow i can say that this is another great article as expected of this blog.Bookmarked this site.. Howard Stern net worth

    ReplyDelete
  14. Your Desired for True Quality Content, Thanks for Such a Informative Article
    google cloud endpoints
    google cloud endpoints

    ReplyDelete
  15. Cool stuff you have got and you keep update all of us. web design

    ReplyDelete
  16. Hi! Thanks for the great information you havr provided! You have touched on crucuial points! wordpress guide

    ReplyDelete
  17. Valuable post, thank you for this informative info. Keep sharing Professionele webshop laten bouwen

    ReplyDelete
  18. So when you're hoping to find a fabulous web designer, the absolute first thing you must check is designing administrations that are quality situated.Webdesign

    ReplyDelete
  19. This was really an interesting topic and I kinda agree with what you have mentioned here! best web development company

    ReplyDelete
  20. This is the type of information I’ve long been trying to find. Thank you for writing this information. buy 250 instagram likes uk

    ReplyDelete
  21. When it has to do with web design, you own a couple of alternatives. WebDesign could possibly be understood as a practice of designing and creating web pages and web websites. web desing service

    ReplyDelete
  22. Free online games… [...]First of all I want to say excellent blog! I had a quick question which I’d like to ask if you do not mind. I was interested to find out how you center yourself and clear your thoughts prior to writing. I have had difficulty clearing my mind in g… new york website design company

    ReplyDelete
  23. Aw, it was a very good post. In idea I would like to devote writing such as this furthermore,?¡ìC spending time and specific work to produce a great article?- nonetheless so what can I say?- I waste time alot and never at all seem to obtain one thing completed. website design company nyc

    ReplyDelete
  24. Truth be told, they can be expensive, so begin putting resources into a little cost, with the goal that you won't wind up getting to your ledger. Novices can pick downpour explicit seedboxes.Danny

    ReplyDelete
  25. It’s difficult to get knowledgeable people within this topic, however, you appear to be guess what happens you’re dealing with! Thanks website designer nyc

    ReplyDelete
  26. This put up is totaly unrelated to what I used to be looking google for, however it was indexed on the first page. I guess your doing something right if Google likes you adequate to place you at the first page of a non related search. web design manhattan

    ReplyDelete
  27. This comment has been removed by the author.

    ReplyDelete
  28. This comment has been removed by the author.

    ReplyDelete
  29. Some genuinely fantastic blog posts on this internet site , thankyou for contribution. branding firms san francisco

    ReplyDelete
  30. Hey there! Wonderful stuff, please do tell us when you post again something similar! sf design agency

    ReplyDelete
  31. I appreciate your work , thanks for all the informative blog posts. iphone mockup

    ReplyDelete
  32. This article gives an extensive rundown of favorable circumstances/weaknesses of the two methodologies, which you can weigh against necessities of your applications to meet your business objective/objective. 먹튀검증

    ReplyDelete
  33. Thanks for making the honest attempt to speak about this. I believe very robust approximately it and want to read more. If it’s OK, as you gain more in depth wisdom, would you thoughts adding extra articles similar to this one with additional information? It might be extremely useful and useful for me and my friends. web design agency san francisco

    ReplyDelete
  34. We have a well-defined process and a dedicated team that will keep you well informed before every step we take. We make sure to get you the top quality website that result in more quality leads and sales. web development services in usa

    ReplyDelete
  35. very nice post, i definitely enjoy this fabulous website, persist with it web designer san francisco

    ReplyDelete
  36. I have been reading out many of your articles and i can claim pretty nice stuff. I will make sure to bookmark your blog. website design san francisco

    ReplyDelete
  37. Completely I share your opinion. In it something is also to me this idea is pleasant, I completely with you agree. website design san francisco

    ReplyDelete
  38. Excellently written article, doubts all bloggers offered the same content because you, the internet is a greater place. Please keep it up! web design agency san francisco

    ReplyDelete
  39. nick website content. I bookmarked it to my bookmark site list and will also be checking back soon. website design firms san francisco

    ReplyDelete
  40. they all are tired from white teeth thats why they put gold or silver teeth!!!! los angeles web design

    ReplyDelete
  41. thank you for sharing!. “Nothing is easy to the unwilling.” by Nikki Giovanni.. web design agencies los angeles

    ReplyDelete

Real Time Web Analytics