×

iFour Logo

What is Routing in ASP.NET Core MVC?

Kapil Panchal - November 11, 2020

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

  • play
  • pause
  • pause
What is Routing in ASP.NET Core MVC?

The routing is a mechanism in which it inspects the incoming Requests path and then map that request to the controllers and action methods. This mapping is done by the routing rules which are defined for the application. We can do this by add the Routing in Middleware to the request processing pipeline.

So, this Framework maps the incoming Request and URL to the Controllers action methods based on the routes configured in your application. You can configure the multiple routes for your application and for each route you can also set some specific configurations such as default values, constraints, message handlers, etc.

There are two types of routing:

  • Conventional Routing
  • Attribute Routing

How Routing Works in ASP.NET Core?


routin

Figure:Routing in ASP.NET Core

When the Request arrives at the Routing Middleware it does the following steps.

  • It parses the URL.
  • Search for the matching Route in the RouteCollection.
  • If it finds the route then it passes the control to RouteHandler.
  • If the route is not found, it gives up and invokes the next Middleware.

What is a Route?


The Route is similar to a roadmap. We used a roadmap to reach our destination similarly, the ASP.NET Core apps uses the Route to reach the controller action.

  • Each Route contains Name, URL Pattern (Template), Defaults and Constraints.
  • The URL Pattern is compared to the incoming URLs for a comparison. An example of URL Pattern is {controller=Home}/{action=Index}/{id?}
  • The Route is defined in the Microsoft.AspNetCore.routing namespace.

What is a Route Collection?


The Route Collection is a collection of all the Routes in the Application. The app maintains a single in-memory collection of Routes and Routes are added to this collection when the application starts. The Routing Module looks for a Route that matches the incoming request URL on each available Route in the Route collection.

The Route Collection is defined in the Microsoft.AspNetcore.routing namespace

What is a Route Handler?


The Route Handler is a component that decides what to do with the route.The routing Engine locates the Route for an incoming request and it invokes the associated RouteHandler and passes the Route for further processing. Route handler is a class which implements the IRouteHandler interface.In the ASP.NET Core, Routes are handled the MvcRouteHandler.

MVCRouteHandler


This is a default Route Handler for the ASP.NET Core MVC Middleware.The MVCRouteHandler is a registered when we register the MVC Middleware in the Request Pipeline. You can override and create your own implementation of the Route Handler.

The MVCRouteHandler is defined in the Microsoft.AspnetCore.mvc namespace.MVCRouteHandler is responsible for invoking the Controller Factory, which in turn creates the instance of the Controller associated to Route. The Controller then takes over and invoke the Action method to generate the View and Complete the Request.

Conventional Routing in ASP.NET Core


The conventional routing is determined based on the conventions defined in the route templates which will map the incoming Requests path to controllers and their action methods. This convention based to routes are defined within the Configure method of the Startup.cs class file.

The conventional Routing establishes a convention for the URL path, such that given a template:

  • First token maps to a controller
  • Second token maps to an action
  • Third token maps to the optional id action parameter

Attribute Routing in ASP.NET Core


This route is determined based on the attributes which are configured either at the controller level or at the action method level and we can use both Conventional Routing and Attribute Routing in a single application.

Attribute routing maps the URLs by applying routing template directly on the controller and action. There is an existence of controller and action in the template is not mandatory for the attribute routing, as they don’t play any part in the routing process.

We can use the [Route] or [HttpGet] (and other verbs) attributes to specify templates. This template can also have literals and tokens (except for controller and action tokens).

Attribute apply to the controller are merged with those on an action for E.g.In the HomeController, PageOne action can be access via /home/one URL.

Creating a Simple Routing Example in Asp.Net Core MVC project


Step 1: -Open visual studio and click on File ->New->Project menu option

A new Project Dialog will open.

project_menu

Figure:Project Menu

Step 2:-Then, select ASP.NET WEB Application (.NET Framework)

Step 3:- Enter project name RoutingDemo1 in the Name Field and click ok to continue and you will see the dialog.

asp_template2

Figure: ASP.NET Templates

Step 4: - Select Empty option and check the MVC checkbox then click Ok

step 5: - select the MVC 5 Controller -> Empty option and click on ADD button The Add controller dialog will open.

scaffold

Figure:Scaffold

Step 6: - set the Name to StudentController and click on add button

student_controller2

Figure:Student Controller

StudentController.cs

namespace Routing_Demo.Controllers
{
public class StudentController : Controller
  {
      // GET: Student
      public ActionResult student()
      {
          return View();
      }
  }
}

Searching for Hire ASP.NET Developer? Your Search ends here.

Create a View


Right-click on the Method Add View.

add_view3

Figure:Add View

We have a Created a Student Empty View and unchecked the use of a layout page checkbox in Student Folder.

Student.cshtml

In Views/Student/Student.cshtml, replace the contents of the file with the following code to replace the text about ASP.NET and MVC with text about thisapplication

STUDENT INDEX ACTION


RouteConfig.cs

Once these are in place, let’s change the route name is default1 and url is api in the RouteConfig.cs

publicclassRouteConfig
{
publicstaticvoidRegisterRoutes(RouteCollection routes)
    {
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
  
    routes.MapRoute(
         name: "Default1",
         url: "api/",
         defaults: new{ controller = "Student", action = "student", id = UrlParameter.Optional }
         );

      }
}

Now let’s run the application. We can see the callstudent () method of the StudentController.

student_actionindex

Conclusion


Routing is a process through which the application matches an incoming URL path and executes the corresponding action methods. The use of routing is middleware to match the URLs of incoming requests and map to specific action methods. Here in this blog, you have learned about the types of Routing and its working.

What is Routing in ASP.NET Core MVC? The routing is a mechanism in which it inspects the incoming Requests path and then map that request to the controllers and action methods. This mapping is done by the routing rules which are defined for the application. We can do this by add the Routing in Middleware to the request processing pipeline. So, this Framework maps the incoming Request and URL to the Controllers action methods based on the routes configured in your application. You can configure the multiple routes for your application and for each route you can also set some specific configurations such as default values, constraints, message handlers, etc. There are two types of routing: Conventional Routing Attribute Routing How Routing Works in ASP.NET Core? Figure:Routing in ASP.NET Core When the Request arrives at the Routing Middleware it does the following steps. It parses the URL. Search for the matching Route in the RouteCollection. If it finds the route then it passes the control to RouteHandler. If the route is not found, it gives up and invokes the next Middleware. What is a Route? The Route is similar to a roadmap. We used a roadmap to reach our destination similarly, the ASP.NET Core apps uses the Route to reach the controller action. Each Route contains Name, URL Pattern (Template), Defaults and Constraints. The URL Pattern is compared to the incoming URLs for a comparison. An example of URL Pattern is {controller=Home}/{action=Index}/{id?} The Route is defined in the Microsoft.AspNetCore.routing namespace. What is a Route Collection? The Route Collection is a collection of all the Routes in the Application. The app maintains a single in-memory collection of Routes and Routes are added to this collection when the application starts. The Routing Module looks for a Route that matches the incoming request URL on each available Route in the Route collection. The Route Collection is defined in the Microsoft.AspNetcore.routing namespace Read More: Understanding Action Filters In Asp.net MVC What is a Route Handler? The Route Handler is a component that decides what to do with the route.The routing Engine locates the Route for an incoming request and it invokes the associated RouteHandler and passes the Route for further processing. Route handler is a class which implements the IRouteHandler interface.In the ASP.NET Core, Routes are handled the MvcRouteHandler. MVCRouteHandler This is a default Route Handler for the ASP.NET Core MVC Middleware.The MVCRouteHandler is a registered when we register the MVC Middleware in the Request Pipeline. You can override and create your own implementation of the Route Handler. The MVCRouteHandler is defined in the Microsoft.AspnetCore.mvc namespace.MVCRouteHandler is responsible for invoking the Controller Factory, which in turn creates the instance of the Controller associated to Route. The Controller then takes over and invoke the Action method to generate the View and Complete the Request. Conventional Routing in ASP.NET Core The conventional routing is determined based on the conventions defined in the route templates which will map the incoming Requests path to controllers and their action methods. This convention based to routes are defined within the Configure method of the Startup.cs class file. The conventional Routing establishes a convention for the URL path, such that given a template: First token maps to a controller Second token maps to an action Third token maps to the optional id action parameter Attribute Routing in ASP.NET Core This route is determined based on the attributes which are configured either at the controller level or at the action method level and we can use both Conventional Routing and Attribute Routing in a single application. Attribute routing maps the URLs by applying routing template directly on the controller and action. There is an existence of controller and action in the template is not mandatory for the attribute routing, as they don’t play any part in the routing process. We can use the [Route] or [HttpGet] (and other verbs) attributes to specify templates. This template can also have literals and tokens (except for controller and action tokens). Attribute apply to the controller are merged with those on an action for E.g.In the HomeController, PageOne action can be access via /home/one URL. Creating a Simple Routing Example in Asp.Net Core MVC project Step 1: -Open visual studio and click on File ->New->Project menu option A new Project Dialog will open. Figure:Project Menu Step 2:-Then, select ASP.NET WEB Application (.NET Framework) Step 3:- Enter project name RoutingDemo1 in the Name Field and click ok to continue and you will see the dialog. Figure: ASP.NET Templates Step 4: - Select Empty option and check the MVC checkbox then click Ok step 5: - select the MVC 5 Controller -> Empty option and click on ADD button The Add controller dialog will open. Figure:Scaffold Step 6: - set the Name to StudentController and click on add button Figure:Student Controller StudentController.cs namespace Routing_Demo.Controllers { public class StudentController : Controller { // GET: Student public ActionResult student() { return View(); } } } Searching for Hire ASP.NET Developer? Your Search ends here. See here Create a View Right-click on the Method Add View. Figure:Add View We have a Created a Student Empty View and unchecked the use of a layout page checkbox in Student Folder. Student.cshtml In Views/Student/Student.cshtml, replace the contents of the file with the following code to replace the text about ASP.NET and MVC with text about thisapplication STUDENT INDEX ACTION RouteConfig.cs Once these are in place, let’s change the route name is default1 and url is api in the RouteConfig.cs publicclassRouteConfig { publicstaticvoidRegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default1", url: "api/", defaults: new{ controller = "Student", action = "student", id = UrlParameter.Optional } ); } } Now let’s run the application. We can see the callstudent () method of the StudentController. Conclusion Routing is a process through which the application matches an incoming URL path and executes the corresponding action methods. The use of routing is middleware to match the URLs of incoming requests and map to specific action methods. Here in this blog, you have learned about the types of Routing and its working.
Kapil Panchal

Kapil Panchal

A passionate Technical writer and an SEO freak working as a Content Development Manager at iFour Technolab, USA. With extensive experience in IT, Services, and Product sectors, I relish writing about technology and love sharing exceptional insights on various platforms. I believe in constant learning and am passionate about being better every day.

Build Your Agile Team

Enter your e-mail address Please enter valid e-mail

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 
Blog Our insights
10 Executive Dashboard Examples for Consultants and CEOs
10 Executive Dashboard Examples for Consultants and CEOs

There is a principle behind every business. “If you don’t keep track of essentials, you won’t get clear direction, eventually causing your company to stumble.” To manage this scenario,...

How Spatial Data Analysis Improves Healthcare
How Spatial Data Analysis Improves Healthcare

Do you know when geospatial analysis took traction in healthcare? It was when John Snow, a London-based physician, used it to analyze the spread of cholera, which ultimately proved...

4 Types of Power BI Dashboards: Analytical, Strategic, Operational, and Tactical
4 Types of Power BI Dashboards: Analytical, Strategic, Operational, and Tactical

One interesting aspect you truly love about Power BI, as a CTO, is how it lets you step back and see the bigger picture of your business. Isn’t it? Without getting bogged down in minute...