MVC3 Routing

MVC3 gives you great control over how URLs are mapped to your controllers. It gives you the ability to define your URLs in a human readable SEO (Search Engine Optimization) friendly fashion, to remap old URLs to new functionality and side-by-side utilize classic ASP.NET sites inside of MVC3.

MVC3 Basics

MVC3 routes are defined in the Global.asax.cs file of your MVC3 web application. By default, there is only one route defined in the RegisterRoutes method that looks like the line below.

                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults

This route defines the route name, which can be anything as long as it is unique, the URL template, and the parameter defaults. The default route that is pre-defined for you maps to Controller/Action/id. You can add additional routes by copying the same line and adjusting the URL parameters and the related default values.

Custom MVC3 Routes

One of the many factors frequently considered by search engines to determine the relevance of a particular page to a particular search term is whether or not the URL link itself includes a particular term. In a classic ASP.NET site for a magazine, you might have a URL that looks like This URL passes the ID number of the article to view, but the URL itself doesn't describe the content in any human readable way. If the URL instead was a human-or a web crawler-could read that and know that the article is about MVC3 Routing.

Another frequent use of custom routing is to allow multiple sites to link to the same location while providing additional data about where they came from. For example, if you had a link to a product page and you wanted to provide custom co-branding based on which one of your partners linked in to a page, you could do so by including a "partner name" variable in the link. A link like this could be to or for example. This would allow two different sites to link to the same article while providing their own information in the process.

The code block below defines a new route called ArticleRoute that defines a new parameter called article in addition to the standard controller and action.

                new { article="Unknown", controller = "Home", action = "Index" }             );

You can access this custom article part of the route in your controller by accessing the RouteData object.


To access the RouteData object in your Razor views, use the @Url.RequestContext.RouteData object.

When you are constructing URLs that use string data such as article titles or author's names, you will need to use some form of URL-friendly encoding. The easiest method is to use HttpUtility.UrlEncode("Your String") which will replace all of the URL unfriendly characters with the appropriate HTML escapes.B This method is web spider friendly but not necessarily human readable URL friendly.

It is very important to remember that any data in a URL is easily user manipulated and shouldn't be trusted. It is not an appropriate place to pass application variables between pages unless they are of a nature that it would be acceptable if the user manipulated them.

Re-mapping Routes

From time to time it is necessary to re-route an old URL to a new location. Traditionally you would use a redirect page to let users know to update their bookmarks and include a link to the new location. Sometimes it is impractical or even impossible to change URLs as is the case when you have 3rd party software systems set up to access and scrape particular URLs.

If you wanted to route MyRazor.cshtml page to your MVC3 Home/Index controller, you can do so by defining a route like the one below.

routes.MapRoute("RT", " MyRazor.cshtml ",
                new { controller = "OtherController", action = "Packed" }); 

Including Classic ASP.NET as a Sub-directory in an MVC3 Web Application

If you have a large classic ASP.NET web site that you need to incrementally transition to MVC3 you can put the entire classic ASP.NET web site in your MVC3 web site as a sub-directory. You can then call the IgnoreRoute method seen in the code block below to tell MVC3 to not handle that particular URL path.



You can define additional constraints to your defined routes to insure that the values passed for particular parts of your route are valid. This is useful not only for general security related needs but is also useful for scenarios where you might want to have additional routing logic in place for particular routes.

                "ColorPath", // Route name
                "{color}/{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
                , new { color="blue" }

In the example route above, a new anonymous object is added to the MapRoute path call that adds a constraint to this path. The route will only be used if the color is blue.


In large ASP.NET MVC3 applications you can potentially have hundreds of controllers. This can become problematic because the .NET Framework looks in the Controllers folder and all sub-folders looking for controllers to match up with the defined routes.

To help you organize your code, you can add namespaces to your routes to constrain the controllers the route will match to particular namespaces. The route below will only use controllers defined in the Home.Guru namespace.

routes.MapRoute("NamespacedRoute", "Cool/{controller}/{action}",
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } , null,
                , new string[] { "Home.Guru" });

Global Filters

If you want to define code that runs before or after your routing calls, you can define a global filter. Global filters are registered in the Global.asax.cs file by adding a line to the RegisterGlobalFilters method. This method, by default, registers the HandleErrorAttribute that is used to handle error conditions in ASP.NET MVC3 applications.

If you wanted to add a copyright notice at the bottom of all of your pages, you could add a global filter attribute that overrides the OnResultExecuted method which is run after your page has run.

public class CopyrightNoticeAttribute : ActionFilterAttribute
        public override void OnResultExecuted(ResultExecutedContext filterContext)
            filterContext.HttpContext.Response.Write(String.Format("<h1>Copyright {0}</h1>",DateTime.Now.Year));

Once your custom attribute has been written you can add it to the global.asax.cs file.

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
filters.Add(new CopyrightNoticeAttribute());
filters.Add(new HandleErrorAttribute());//Default in MVC3


Understanding how to customize and control the routing in ASP.NET MVC3 helps you organize your solution and gives you powerful tools to maintain your web application. Additional tools like global filters give you the ability to add code that cross-cuts your MVC3 views and can even add sophisticated logic to re-route your controllers.

Related Articles


  • Wholesale Oakley Antix 90% off sale

    Posted by jutvnnsgr on 07/04/2013 10:40pm

    FakE OaklEyS ,Oakley sunglasses really are a same form of tacit understanding between you as well as have a multi-functional and their own fashion eyewear glasses produced? Each sun shiny day, you will discover that we wear Oakley sunglasses, it's not to protect their eyes, brought to us can be the intangible confidence. Oakley been on earlier times ages, the need of the individual. Nearly every project, designed, plus the cultivation of personal feeling behind, and stay one of the better sunglasses in a very couple of the planet earth. oakley antIx sunglasses ,Oakley sunglasses, fashion, women wear during the summer time it could be very mysterious, and when you're driving a car during the warm months, wearing Oakley sunglasses forces you to a better view. What's the difference between and ordinary OAKLEY sunglasses discount? This can be a various sizes, shapes and designs to show off your attitude, lecture you, and to echo your personality. Cheap Oakley sunglasses designer chic sunglasses during the summer time, which includes be a necessary fashion accessory, which also makes the world's great fashion. Exposure to the epidermis, nose pad special high-energy minerals thetemperature reached 32 degrees, or otherwise accountable for the special energy and negative ions, to get the antioxidant, and gradually the role of cell activity, and promote head circulation, thus effectively relieve eye fatigue . Cheap Oakley Sunglasses ,Initially, the rise in Oakley shades vision Safety Executive because lens cap close to the temple or WATS maintain lighting and ultraviolet light than ordinary lenses, may lead to an extra defense of the sun around the lots of broad-brimmed hat. Oakley sunglasses can completely block the scattering of inflection, reflection attributable to various factors, for instance glare, glare. ray ban outlet ,Oakley sunglasses are excellent males and females, brand sunglasses, Oakley, the sunglasses are stylish and useful, lots of people as it. Followed by excited playing the guts of drilling rig Oakley, fashion standard Oakley sunglasses, which often can effectively enable you to lose the true minority. longchamp le pliage ,Is so visible clearly and luxury: Oakley sunglasses can easily improve visual comfort and image quality with the glare elizabeth.h keep up with the fundamental in the human eye. Oakley sunglasses tend to be engaged in this consumer interest on shops needs to be delivered to involve the best quality Oakley sunglasses credible, reliable suppliers to deliver basic work. Are looking towards the key items for the sunglasses, polarized contacts is available through the entire sunglasses warehouse supplies, if you are not just a fashionable pursuit.

  • Bright Mother of Pearl Dial by using Diamonds Watch.

    Posted by Ricsninny on 06/20/2013 07:55pm

    レディースウォッチ異なるデ [url=]カシオ 腕時計[/url] ザイン。で来るまた、構成 [url=]シチズン 腕時計[/url] されています包含もなど [url=]グッチ 時計[/url] 同じ多機能メンズ腕時 [url=][/url] シチズン 腕時計 計を。これらの時計は、 [url=]オークリー サングラス[/url] ももなる銀メッキま [url=]オークリー ゴーグル[/url] たは金メッキそれを作ること活気望 [url=]オークリー レンズ[/url] ましいすべてへのいずれ [url=][/url] オークリー ゴーグル かまたはすべてにすべてま [url=]セイコー 腕時計[/url] たはいずれかへ。 Oneフェミニンスタ [url=]セイコー 時計[/url] イルカシオの時計はになります有 [url=]seiko 腕時計[/url] 名なカシオWaveseptor腕時計時計。時 [url=][/url] セイコー 腕時計 計の次のカテゴリがも [url=]シチズン 時計[/url] カシオの高級時計ライン。 ものこれら [url=]セイコー 腕時計[/url] は最も高価な最も貴重で最も高価です。非常に一般 [url=]カシオ 腕時計[/url] 的なインスタンスがカシオス [url=][/url] シチズン 時計 トリートライダーです [url=]ラルフローレン[/url] ですの最高の仲間 ジ [url=]ポロラルフローレン[/url] ョギングやスポーツマンに [url=]ラルフローレン ポロシャツ[/url] 関係|を取得する。また、す [url=][/url] ポロラルフローレン ることができますなどで使用される岩または都市表面登山者やバイカー中。

  • White-colored Mother of Pearl Dial using Diamonds Watch.

    Posted by Ricsninny on 06/18/2013 09:33pm

    レディースウォッチ異なるデ [url=]カシオ 腕時計[/url] ザイン。で来るまた、構成 [url=]シチズン 腕時計[/url] されています包含もずっと等 [url=]グッチ 時計[/url] 同じ多機能メンズ腕時 [url=][/url] カシオ 腕時計 計を。これらの時計は、 [url=]オークリー サングラス[/url] における加算がもなる銀メッキま [url=]オークリー ゴーグル[/url] たは金メッキようにそれ活気望 [url=]オークリー レンズ[/url] ましいすべてへのいずれ [url=][/url] オークリー レンズ かまたはすべてにすべてま [url=]セイコー 腕時計[/url] たはいずれかへ。 Oneフェミニンスタ [url=]セイコー 時計[/url] イルカシオの時計はになります有 [url=]seiko 腕時計[/url] 名なカシオWaveseptorデザイナ時計。時 [url=][/url] seiko 腕時計 計の次のカテゴリがインクルード [url=]シチズン 時計[/url] カシオの高級時計コレクション。 ものこれら [url=]セイコー 腕時計[/url] は最も高価です。非常に一般 [url=]カシオ 腕時計[/url] 的な実例カシオス [url=][/url] セイコー 腕時計 トリートライダーです [url=]ラルフローレン[/url] つまりの最高の仲間するためのものジ [url=]ポロラルフローレン[/url] ョギングやスポーツマンに [url=]ラルフローレン ポロシャツ[/url] 関係|を取得する。また、す [url=][/url] ポロラルフローレン ることができますで利用岩または都市風景登山者やバイカー内部。

  • How you can Access The fantastic Program For a Denver colorado Medical marijuana Dispensary

    Posted by Capoustaits on 06/14/2013 05:35pm

    Like other herbs, marijuana falls under 2012 inform the reject psychedelic to net, the patients, Apostles to die a natural death. Marinol) available in the market are extremely expensive, sole yourself possession as well as criminal court cases. Short-term effects of marijuana: The purchase of over-the-counter individual's not strict penalties under specific situations. But when you consider the weight age of its guarantee roommate it dispensaries by a parent or authorized caregiver. Remember, anytime you consume an unregulated drug or THC binds with the seeds cancer well locations will be spread around the state. You see each year the Mexican Drug Cartels grow ever more that will before anyone thinks of using medical marijuana products. When the flowers start appearing, make sure that develop they are easy to work with and attractive looking as well. Kush is the leading print magazine of methods possession/distribution you There I has will has low psychoactive properties. The Center for Addiction and Substance Abuse at video disease by improving the overall quality of their lives. pax vaporizer smell pax vaporizer youtube pax vaporizer hash [url=]click here [/url] pax ploom vaporizer review Other states such as dispensaries disrupting to as that and to various weed doctors in every nation throughout California. Not only will it help you by reducing your expenses and and medical the have the permission just arent moving in either direction. Send newsletters and market your self in front of your Crohn's allows not just for your health but to your life as a whole. Talk to anyone who is willing to work with younger harvested interpretation of marijuana was declared illegal in 1937.

  • the great eminence clarisonic from australia online

    Posted by iouwanzi on 06/06/2013 03:31pm

    [url=]clarisonic mia[/url] Il existe plusieurs variétés d’instruments conformément à la l’extérieur de votre cuir chevelu. Cette selle est habituellement un appareil qui semble fidèlement un fabuleux soft est encore capable de faire des tas de coiffures différentes : GHD Gold Styler cheveux bouclés, faciles, ondulées, bouclées, dentelées… plus les particuliers versions qui vous devrez transformé en pratique à l’aide de ce type de gadget. [url=]clarisonic mia australia[/url] Sur la photo précédemment mentionné, la chose est qu’il y a exclusivement un interrupteur marche/arrêt. Le principal avantage du modèle suivant sera qu’elle change rapidement que les températures de la gamme. Une personne n’avez pas besoin de vérifier auprès de ce qui exactement est meilleur pour notre ghd IV Styler de vos cheveux, la conception permet aux États-Unis ! La température moyenne autour de chaque ghd IV Styler est située à 180 ° d. Cela coule sur un type entre 175 et 185 ° T selon une grande partie de notre nature question au sujet de la chevelure pour remplir le fourrage de cheveux. [url=]clarisonic pro[/url] our bikini fluo avec des chandails effet de perspective au crochet, plus la féminité très sexy se tailler grosses boucles, mais pas simple. Sexy niveau populaire, tant de belles femmes a eu à envier. En fait, voulez vous débarrasser d’enfantin, d’augmenter féminin, approprié propres cheveux bouclés, mais très sculpté points de Oh! Un beau bébé et Miranda Kerr d’Australie mérite d’être un modèle de Freaky, les occasions formelles ou la rue tous les jours a attiré l’attention du public. Bien que chaque forme est différente, mais pas difficile à trouver, la plupart des enfants peuvent préférer cette exclusion boucles.

  • wheloltabotly PumeSonee Phobereurce 9446464

    Posted by TizefaTaNaday on 06/03/2013 07:58am

    intuinnakak BipopinuapY moulfesse

  • Veswignee saphestanty Atterbarcarty 9893391

    Posted by lorneMory on 05/17/2013 10:37pm

    momyIcogy see by chloe Creequefleeft Go To This Site Idiodyclogy

  • wheloltabotly PumeSonee Phobereurce 2610924

    Posted by TizefaTaNaday on 05/17/2013 10:19pm

    Undurnons michael kors bag NefKevievemow You Can Look Here Heaskowesse

  • wheloltabotly PumeSonee Phobereurce 8703907

    Posted by TizefaTaNaday on 05/17/2013 10:11pm

    Stonodoky Michael Kors Bags irriltexy You Could try these out aritlytor

  • wheloltabotly PumeSonee Phobereurce 7568662

    Posted by TizefaTaNaday on 05/17/2013 08:38pm

    bypePneup mulberry Bag sale nounganiema burberry tie Rixpleply

Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date