Configuring Routes

ASP.NET MVC routes are responsible for determining which controller method (otherwise known as a controller action) to execute for a given URL. They consist of the following properties:
Unique name
A name may be used as a specific reference to a given route
URL pattern
A simple pattern syntax that parses matching URLs into meaningful segments
An optional set of default values for the segments defined in the URL pattern
A set of constraints to apply against the URL pattern to more narrowly define the URLs that it matches. The default ASP.NET MVC project templates add a generic route that uses the following URL convention to break the URL for a given request into three named segments, wrapped with brackets ({}): “controller”, “action”, and “id”:


This route pattern is registered via a call to the MapRoute() extension method that runs during application startup (located in App_Start/RouteConfig.cs):

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

In addition to providing a name and URL pattern, this route also defines a set of default parameters to be used in the event that the URL fits the route pattern, but doesn’t actually provide values for every segment.
For instance, following Table contains a list of URLs that match this route pattern, along with corresponding values that the routing framework will provide for each of them.

URL Controller Action ID
/Product/Details/12 ProductController Details 12
/Product/Details ProductController Details
/Product ProductController Index
/ HomeController Index

The first URL (/Product/Details/12) in the table is a perfect match because it satisfies every segment of the route pattern, but as you continue down the list and remove segments from the end of the URL, you begin to see defaults filling in for values that are not provided by the URL.


You may also like...