URL Routing with the ASP.NET MVC Framework

Please note: this article was written for the original MVC CTP1 preview in 2007 and is horrifically out of date.

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.

Route Mapping

Lets start by looking at the default route created when starting a new MVC project.

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:

Thus the id of '203' can be extracted inside the controller.

Ignoring URLs

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.

This code tells MVC to ignore all requests for webforms apsx pages.

Registration

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.