Click here to Skip to main content
Click here to Skip to main content

Routing in MVC

By , 4 Sep 2013
Rate this:
Please Sign up or sign in to vote.

Table of Contents

Introduction

This article explains routing in MVC. How a route is executed by the routing engine and how to define a route for a URL.

ASP.NET MVC routing is a pattern matching system that is responsible for mapping incoming browser requests to specified MVC controller actions. When the ASP.NET MVC application launches then the application registers one or more patterns with the framework's route table to tell the routing engine what to do with any requests that matches those patterns. When the routing engine receives a request at runtime, it matches that request's URL against the URL patterns registered with it and gives the response according to a pattern match. Let's see Figure 1.1.

ASP.NET MVC Routing

Figure 1.1 ASP.NET MVC Routing

In Figure 1.1 we can see how the routing engine processes a request and what response it sends. It gives a response according to URL match or not in the route table.

  1. When the request's URL matches any of the registered route patterns in the route table then the routing engine forwards the request to the appropriate handler for that request. Thereafter the route is processed and gets a view on the UI.
  2. When the request's URL does not match any of the registered route patterns then the routing engine indicates that it could not determine how to handle the request by returning a 404 HTTP status code.

Properties of Route

ASP.NET MVC routes are responsible for determining which controller method to execute for a given URL. A URL consists of the following properties:

  • Route Name:A route is a URL pattern that is mapped to a handler. A handler can be a controller in the MVC application that processes the request. A route name may be used as a specific reference to a given route.
  • URL Pattern: A URL pattern can contain literal values and variable placeholders (referred to as URL parameters). The literals and placeholders are located in segments of the URL that are delimited by the slash (/) character.
  • When a request is made, the URL is parsed into segments and placeholders, and the variable values are provided to the request handler. This process is similar to the way the data in query strings is parsed and passed to the request handler. In both cases variable information is included in the URL and passed to the handler in the form of key-value pairs. For query strings both the keys and the values are in the URL. For routes, the keys are the placeholder names defined in the URL pattern, and only the values are in the URL.

  • Defaults:When you define a route, you can assign a default value for a parameter. The defaults is an object that contains default route values.
  • Constraints: A set of constraints to apply against the URL pattern to more narrowly define the URL that it matches.

Understand the Default Route

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.

url: "{controller}/{action}/{id}"

This route pattern is registered via call to the MapRoute() extension method of RouteCollection.

Default Routes for MVC Application

Figure 1.2 Default Routes for MVC Application

When the MVC application launches the Application_Start() event handler of the global.asax execute that call the RegisterRoutes() method from RouteConfig class under App_Start directory (App_Start/RouteConfig.cs). The RegisterRoutes() route has a parameter that is a collection of routes called the RouteCollection that contains all the registered routes in the application. The Figure 1.2 represents the default method that adds routes to the route table.

Routing with an Example

When the application starts up, ASP.NET MVC discovers all of the application's controllers by searching through the available assemblies for a class that implements the System.Web.Mvc. The IController interface or derived from a class that implements this interface and whose class names end with the suffix Controller. When the routing framework uses this list to determine which controller it has access to, it chops off the Controller suffix from the entire controller class names.

In the previous article CRUD Operations Using the Repository Pattern in MVC I implemented Create, Read, Update, and Delete operations on a book entity. So we will use this example to understand URL routing. Our default route is the same as in Figure 1.2 for CRUD applications also.

URL Controller Action Id
http://localhost:4736/ HomeController Index  
http://localhost:4736/Book/ BookController Index  
http://localhost:4736/Book/Create BookController Create  
http://localhost:4736/Book/Edit/2 BookController Edit 2
Table 1.1 Request's URLs that match our default route pattern

The last request's URL (http://localhost:4736/Book/Edit/2) in the table 1.1 is a perfect match to the registered default URL pattern because it satisfies every segment of the route pattern, but when we don't provide a complete request's URL then the routing engine automatically calls the controller and action method as per the default route pattern.

Conclusion

The controller and action values in the route are not case-sensitive. URL route patterns are relative to the application root, so they don't need to start with a forward slash (/) or virtual path designator (~/).

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Sandeep Singh Shekhawat
Software Developer Jaipur
India India
I am ASP.NET/ASP.NET MVC Developer.
 

Achievements

C# Corner MVP (2013 and 2014)
 

Awards

 
Article of the Day on Microsoft's site http://www.asp.net/community/articles on 07 March 2014.
Article of the Day on Microsoft's site http://www.asp.net/community/articles on 18 March 2014.
Article of the Day on Microsoft's site http://www.asp.net/community/articles on 21 March 2014.
Article of the Day on Microsoft's site http://www.asp.net/community/articles on 09 April 2014.
 
3rd Best C# Article of January 2014
4th Best Web Dev Article of January 2014
Follow on   Twitter

Comments and Discussions

 
GeneralMy vote of 4 PinmemberMember 101040285-Sep-13 15:51 
GeneralRe: My vote of 4 PinprofessionalSandeep Singh Shekhawat13-Jan-14 2:01 
GeneralMy vote of 5 PinmemberHumayun Kabir Mamun5-Sep-13 1:03 
GeneralRe: My vote of 5 PinprofessionalSandeep Singh Shekhawat13-Jan-14 2:00 
GeneralMy vote of 5 PinmemberVolynsky Alex5-Sep-13 0:31 
GeneralRe: My vote of 5 PinprofessionalSandeep Singh Shekhawat13-Jan-14 2:00 
GeneralVery simple, but needs more PinmemberNitinSingh4-Sep-13 21:18 
GeneralRe: Very simple, but needs more PinprofessionalSandeep Singh Shekhawat13-Jan-14 2:00 
GeneralMy vote of 3 PinmemberTridip Bhattacharjee4-Sep-13 20:44 
GeneralRe: My vote of 3 PinprofessionalSandeep Singh Shekhawat13-Jan-14 1:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.140415.2 | Last Updated 4 Sep 2013
Article Copyright 2013 by Sandeep Singh Shekhawat
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid