Routing is vital to MVC. Routing defines mappings between URL and ActionMethod - that would handle request to that URL. For example, following route mapping defines that when a user hits "http://mysite/shopping/cart", call OrderController's ShowCart() method to handle this request.
Said that "Routes should be defined explicitly", over a period of time your routes may grow significantly. It would be wise to re-factor and organize your routes such that they are manageable and in some way logically grouped so that it's pretty easy to locate a Route.
routes.MapRoute("cart", "shopping/cart", new { controller = "Order", action = "ShowCart" });
Placing Routes
A common place to put route mappings is in RegisterGlobalFilters method inside Global.asax:public class MvcApplication : System.Web.HttpApplication { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { //Define Routes routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Login", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); } }
Often, you would use generic route "Controller/Action/Parameters" (as in aforesaid code) which maps Controller/Action/parameter with URLs tightly. But I prefer to explicitly define all routes (or at least as many as possible) to decouple URL with their handler methods for several reasons listed below:
- No matter how good your architecture is, you would find a need to re-factor it, when it grows. With Routes tightly mapped to methods, you may find difficulty in re-factoring. (without altering URLs)
- You may find a need to change routes for indexing purpose on search-engines or for any other reason as demanded by business people (without altering actions)
- In a complex scenario, you may wish to provide options to marketing team to be able to change routes and define a mechanism to map it with methods (without altering actions)
- You may wish to change URL which is attacked (without altering actions)
- Or any other reason for which you wish to alter either of URL or Method without altering other
Said that "Routes should be defined explicitly", over a period of time your routes may grow significantly. It would be wise to re-factor and organize your routes such that they are manageable and in some way logically grouped so that it's pretty easy to locate a Route.
This post is all about one such approach to organize your Routes.