Serving Industries Worldwide

Innovative Ways - Satisfied Clientele

What is Routing in ASP.NET Core MVC?


Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

 
 

Routing-asp-dot-net

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:

  1. Conventional Routing
  2. 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.

  1. It parses the URL.
  2. Search for the matching Route in the RouteCollection.
  3. If it finds the route then it passes the control to RouteHandler.
  4. 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.

  1. Each Route contains Name, URL Pattern (Template), Defaults and Constraints.
  2. The URL Pattern is compared to the incoming URLs for a comparison. An example of URL Pattern is {controller=Home}/{action=Index}/{id?}
  3. 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:

  1. First token maps to a controller
  2. Second token maps to an action
  3. 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


    

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?

Routing-asp-dot-net

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:

  1. Conventional Routing
  2. 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.

  1. It parses the URL.
  2. Search for the matching Route in the RouteCollection.
  3. If it finds the route then it passes the control to RouteHandler.
  4. 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.

  1. Each Route contains Name, URL Pattern (Template), Defaults and Constraints.
  2. The URL Pattern is compared to the incoming URLs for a comparison. An example of URL Pattern is {controller=Home}/{action=Index}/{id?}
  3. 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:

  1. First token maps to a controller
  2. Second token maps to an action
  3. 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


    

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.