Unlike standard ASP.NET, MVC does not use a directory and file system for URLs. Rather it maps URLs to controller classes in a RESTfull manner. Routing is defined in the Global.asax file.
Lets start by looking at the default route created when starting a new MVC project.
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapRoute
(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
}
RouteCollection.MapRoute() is used to map a route to a controller class. MapRoute() takes a name, a parametrized URL and a parameter object. The parametrized URL represents a pattern. Each URL parameter in the pattern is separated by a constant (in this case '/' though you could use any character or characters).
A URL coming in will be matched to the pattern. So if a following URL comes in http://www.rrreese.com/category/purchase/203 it will be matched as follows:
controller: category
action: purchase
id: 203
Controller and action are mapped by default to the controller class and action methods. Any other arbitrary URL parameter can be used, but must be managed manually in code. Inside the controllers the RouteData can be investigated as follows:
Url.RequestContext.RouteData.Values["id"].ToString()
Thus the id of '203' can be extracted inside the controller.
Because the MVC application intercepts and routes all URLs it is necessary to have a way to ignore certain URLs. RegisterRoutes.IgnoreRoute() can be used to achieve this.
routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
This code tells MVC to ignore all requests for webforms apsx pages.
When the MVC application begins the RegisterRoutes() method is called by Application_Start() to build the route table. When a URL request is made MVC iterates through all the routes in the route table until a match is found. If no match is found then a 404 error is found.