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

67 comments:

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

    ReplyDelete
    Replies
    1. Great Article Cloud Computing Projects

      Networking Projects

      Final Year Projects for CSE

      JavaScript Training in Chennai

      JavaScript Training in Chennai

      The Angular Training covers a wide range of topics including Components, Angular Directives, Angular Services, Pipes, security fundamentals, Routing, and Angular programmability. The new Angular TRaining will lay the foundation you need to specialise in Single Page Application developer. Angular Training

      Delete
  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
  42. i use google when i want to do some spanish translation, it is good for general spanish translation,, design firms los angeles

    ReplyDelete
  43. Great write-up, I am a big believer in writing comments on websites to let the blog writers know that they’ve added some thing useful to the world wide web! los angeles web agency

    ReplyDelete
  44. Deal with the composing style, be compact yet not brief and surely not all that longwinded that sleepiness calls. Bluehost review

    ReplyDelete
  45. An advertiser would now be able to focus on a person at the exact time that a buy is going to made. smm panel

    ReplyDelete
  46. Personally, I have found that to get just about the most fascinating topics if this draws a parallel to. top web design companies

    ReplyDelete
  47. wonderful post. Ne’er knew this, regards for letting me know. website design company

    ReplyDelete
  48. This article is very appealing to thinking people like me. It’s not only thought-provoking, it draws you in from the beginning. This is well-written content. The views here are also appealing to me. Thank you. web design company

    ReplyDelete
  49. hi and thanks regarding the particular post ive really been searching regarding this kind of info online for sum time these days hence thanks a lot web design tips

    ReplyDelete
  50. depending on fossil fuel is always a bad idea, we should always concentrate on renewable energy. branding agency los angeles

    ReplyDelete
  51. Nice post! This is a very nice blog that I will definitively come back to more times this year! Thanks for informative post. here

    ReplyDelete
  52. Nonphysical merchandise, for example, programming, can be sent electronically, wiping out the whole vehicle channel. Installments should be possible in new manners.best place to buy a cheap domain name

    ReplyDelete
  53. This is my first time visit to your blog and I am very interested in the articles that you serve. Provide enough knowledge for me. Thank you for sharing useful and don't forget, keep sharing useful info: SEO Agency Vancouver

    ReplyDelete
  54. Thank you because you have been willing to share information with us. we will always appreciate all you have done here because I know you are very concerned with our. sydney wordpress design

    ReplyDelete
  55. Thanks, foг ones marvelous posting! I genuinely enjoyed reading it, you miggһt Ƅe a great author. I wiⅼl made certain to booҝmark your blog and ѡill often come back sometime soon. I want to encoᥙrage yourself to continue your great job, have a nice evening!
    Web Development Course
    best web development courses
    web development classes
    web development course near me
    Web Development Training
    training on web development
    web development training program
    web development training course
    web development summer training

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

    ReplyDelete
  57. Icreativez.pk helps you climb the SERPs and hold on top of your user preferences. Seo Services In Karachi

    ReplyDelete
  58. Once more, web and a couple of work area shopping applications assist you with separating your shopping records by 'Generally required' things like for Coupons. Utilize these web applications and you'll understand the move in your general shopping conduct other than buying and spending designs. besimple.com/

    ReplyDelete
  59. How long has the SEO master been in website architecture?Webdesign

    ReplyDelete
  60. Whenever you've finished the subtleties of your undertaking including the spending plan, time to finish and depiction, you'll be prepared to post your venture for review by consultants.
    Professional graphic design

    ReplyDelete
  61. I get some knowledge after reading this article of about ASP NET MVC. So, i also have some more knowledge about the technology. For this, i want to start a website and want hosting within my budget. One of my friend tells me that i can get hosting from HostGator Shared Web Hosting Black Friday discount. Can i get better deals and plans from this company.

    ReplyDelete

Real Time Web Analytics