In this tutorial we will take a look at ASP.NET MVC Routing which is a very powerful method of handling URL’s in web apps. It should be noted at the outset that R0uting is not exclusive to MVC and can also be used in ASP.NET 4.0 – see ASP.NET 4.0 URL Routing Tutorial for more details (most of the detail provided below is applicable to ASP.NET Routing as well as MVC Routing, although the implementation is slightly different)
ASP.NET MVC Routing serves two main purposes:
- Matching incoming requests and mapping them to a controller action.
- Constructing outgoing URLs which correspond to controller actions.
ASP.NET MVC Routing compared to URL Rewriting
Both Routing and URL ReWriting can create search engine friendly URLs. A key difference, however, is that URL Rewriting is an approach which focuses on a single page at a time. Most ASP.NET URL rewriting schemes rewrite a URL for one page to be handled by another. For example , /product/cars.aspx might be rewritten as: /products.aspx?id=65 .
Routing, by contrast. is a resource-centric view of URLs. A URL represents a resource which is not necessarily a web page. With Routing, this resource is a block of code that executes when an incoming request matches the route. A route determines how a request is dispatched based on characteristics of a URL.
Another difference is that Routing is bidirectional as it also helps in generating URLs by using the same rules used to match incoming URLs. However, ASP.NET Routing never actually rewrites a URL, the URL that a user requests in the browser is the same URL the application sees throughout the request lifecycle.
An ASP.NET MVC app needs a minimum of one route to define how the app should handle requests, complex apps will likely have numerous routes. Route definitions begin with a URL that specifies a pattern the route will match. As well as the route URL, routes may also specify a default value and constraints for parts of the URL. This provides very tight control over how a route matches the incoming request URLs.
In the Application_Start method of the Global.asax.cs file in a ASP.NET MVC Web Application project, there is a call to the RegisterRoutes method. This method is the place where all the routes for the app are registered.
For this tutorial we can remove all the routes in there and enter a single very simple route: