Routing in ASP.NET MVC

By   Calendar icon Jun 13, 2020   Level 1 icon

Description:

We explain how routing works in ASP.NET MVC, how to manage routing and how to use routing patterns in a web application. We present some examples of the implementation of routing.

Preferencesoft

Tags: ASP.NETASP.NET MVC

We explain in this article how routing works in ASP.NET MVC and how to manage it in a web application. We give some examples of routing implementation.

Routing in general

Routing

Routing is a process of interpreting http requests and branching to a controller that performs processing.

Routes

Routes are made up of a template to which the request url is compared and a controller and action selector.

Routing table

A routing table is an internal table that contains the various routes.

How routing works in ASP.NET MVC

In ASP.NET, routing consists of

  • an analysis of the incoming url,
  • a search in a table according to a model,
  • a selection of the corresponding controller and the action to be performed.

In this diagram,

  • R represents the routing system
  • C the controller,
  • M the model,
  • and V the view.

In details, the routing system performs the following steps:

It parses the url, for example domain.com/Home/Page/1 to extract the different parameters of the request, finds the route according to the parameters (pattern matching) in a mapping table containing the declared routes of the application.

If a route is found, execution continues in the method of the corresponding controller, otherwise, a page not found error is sent.

Route configuration

There is a way to interfere with routing at the IIS server level by adding some url rewriting and redirecting rules in the <system.webServer> tag of the web.config file, but we will not cover this topic in this article. article.

In an ASP.NET MVC application, it is possible to define the routing:

By modifying the RouteConfig class of the RouteConfig.cs file located in the App_Start directory, Or by adding routing attributes on top of some method or class of a controller.

Routing template

The routing template is a string that looks like a URI but can contain placeholders delimited by braces

"{controller}/{action}/{id}"

Each placeholder stores the character string behind it if the url matches the pattern.

Here is the default route of a ASP.NET MVC application declared in the file RouteConfig.cs:

routes.MapRoute(  
                name: "Default",  
                url: "{controller}/{action}/{id}",  
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }  
            );

ASP.NET