×

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 mapped 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.

 

Table of Content

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 Dedicated ASP.NET Web 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 mapped 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.   Table of Content 1. How Routing Works in ASP.NET Core? 2. What is a Route? 3. What is a Route Collection? 4. What is a Route Handler? 5. MVCRouteHandler 6.Conventional Routing in ASP.NET Core 7. Attribute Routing in ASP.NET Core 8. Creating a Simple Routing Example in Asp.Net Core MVC project 9. Conclusion 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 Dedicated ASP.NET Web 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.

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

Power Apps vs Power Automate: When to Use What?
Power Apps vs Power Automate: When to Use What?

I often see people asking questions like “Is Power App the same as Power Automate?”. “Are they interchangeable or have their own purpose?”. We first need to clear up this confusion...

Azure DevOps Pipeline Deployment for Competitive Business: The Winning Formula
Azure DevOps Pipeline Deployment for Competitive Business: The Winning Formula

We always hear about how important it is to be competitive and stand out in the market. But as an entrepreneur, how would you truly set your business apart? Is there any way to do...

React 18 Vs React 19: Key Differences To Know For 2024
React 18 Vs React 19: Key Differences To Know For 2024

Ever wondered how a simple technology can spark a revolution in the IT business? Just look at React.js - a leading Front-end JS library released in 2013, has made it possible. Praised for its seamless features, React.js has altered the way of bespoke app development with its latest versions released periodically. React.js is known for building interactive user interfaces and has been evolving rapidly to meet the demands of modern web development. Thus, businesses lean to hire dedicated React.js developers for their projects. React.js 19 is the latest version released and people are loving its amazing features impelling them for its adoption.