Back to: ASP.NET Core Tutorials For Beginners and Professionals
Routing in ASP.NET Core MVC Application
In this article, I will discuss Routing in ASP.NET Core MVC Applications with examples. Please read our previous article discussing ASP.NET Core MVC TempData with Examples. As part of this article, we will discuss the following pointers in detail.
- What is Routing in ASP.NET Core MVC?
- How Does Routing Work in ASP.NET Core?
- What are the different types of Routing supported by ASP.NET Core MVC?
- How is Routing Working in ASP.NET Core?
- Understanding Conventional Based Routing.
What is Routing in ASP.NET Core MVC?
The Routing in the ASP.NET Core MVC Web Application is a mechanism in which it will inspect the incoming HTTP Requests (i.e., URLs) and then map that HTTP request to the controller’s action method. This mapping is done by the routing rules which are defined for the application. We can do this by adding the Routing Middleware to the Request Processing Pipeline.
The ASP.NET Core MVC Framework maps the incoming HTTP Requests, i.e., URLs, to the Controller’s action methods based on the routes configured in your application. You can configure multiple routes for your application, and for each route, you can also set some specific configurations such as default values, constraints, etc. If this is not clear at the moment, then don’t worry; we will discuss each and everything with examples.
How Does Routing Work in ASP.NET Core?
So, in simple words, we can say that Routing is a pattern-matching system that monitors the incoming request and figures out what to do with that request. Typically, it is a way to serve the user’s request. For a better understanding, please have a look at the following diagram.
When the client makes a request, i.e., makes an HTTP Request, then that request is first received by the Routing Engine. Once the Routing engine receives an HTTP Request, the Routing system tries to find out the matching route pattern of the requested URL with already registered routes. Routes contain information about the Controller name, action method name, method type (Get, Post, Put, Patch, Delete), method parameters, route data, etc.
If it finds a matching URL pattern for the incoming request, then it forwards the request to the appropriate controller and action method. If there is no match found for the incoming HTTP request URL Pattern, then it simply returns a 404 HTTP status code to the client. For a better understanding, please have a look at the following diagram.
What are the Different Types of Routing Supported by ASP.NET Core MVC?
We can configure routes in the ASP.NET Core MVC Web Application in two ways. They are as follows:
- Convention-Based Routing
- Attribute-Based Routing.
What is Conventional Based Routing in ASP.NET Core MVC Web Application?
In Conventional Based Routing, the route is determined based on the conventions defined in the Routing Middleware, which will map the incoming HTTP Requests (i.e., URLs) to controller action methods. Before .NET 6, the Convention Based Routes are defined within the Configure method of the Startup class. From .NET 6, you can configure the Convention Based Routes within the Main method of the Program class.
That means the Conventional-Based Routing in ASP.NET Core MVC is a routing mechanism that relies on a set of conventions and default patterns to map the incoming URLs (HTTP Requests) to controller actions. This type of routing is based on predefined naming conventions and doesn’t require explicit route attributes or configuration.
In Conventional-Based Routing, the URL segments and their order are used to determine the controller and action that should handle the request. This approach simplifies routing configuration by leveraging naming conventions and promoting a consistent controller and action structure.
In this approach, one or more conventions are configured for the routing that will be used to match the incoming URL path to the endpoints. In ASP.NET Core applications, these endpoints are nothing but the action methods of the controllers.
What is Attribute-Based Routing in ASP.NET Core MVC Application?
Attribute-Based Routing in ASP.NET Core MVC is a powerful approach to defining URL routes by using Route Attributes directly on our controller actions or controllers themselves. With Attribute-Based Routing, we can specify the routing configuration at a very granular level, making our routing logic more explicit and closely tied to our action methods.
In contrast to conventional-based routing, where routes are configured in a centralized location, attribute-based routing allows you to define routes directly within the code where the associated actions or controllers are located. Using both Conventional Based Routing and Attribute-Based Routing in a Single ASP.NET Core MVC Web Application is also possible.
In this article, we are going to discuss Conventional Based Routing, and in our upcoming articles, we will discuss Attribute-Based Routing in ASP.NET Core MVC Applications.
Understanding Conventional-Based Routing in ASP.NET Core MVC:
In the ASP.NET Core MVC Web Application, the controller action method will handle the incoming HTTP Requests, i.e., URLs. For example, if we issue a request to the /Home/Index URL, then the Index action method of the Home Controller class will handle the request, as shown in the image below.
Similarly, if we issue a request to the /Home/Details/2 URL, then the Details action method of the Home Controller class will handle the request, as shown in the image below. Here the parameter value 2 is automatically mapped to the id parameter of the Details action method.
Now, the question that should come to your mind is, we have not explicitly defined any routing rules for the application. Then how does this mapping is done, i.e., how the /Home/Index URL is mapped to the Index action method, and how /Home/Details/2 URL is mapped to the Details action method of the Home Controller class? This is done by the MVC Middleware Component, which we registered into the Request Processing Pipeline application.
Understanding Routing in ASP.NET Core MVC Application:
So, first, create an ASP.NET Core Application using the ASP.NET Core Model-View-Controller Template. To create an ASP.NET Core Web Application with the Model-View-Controller Project template. First, open Visual Studio 2022 and then click on the Create a new project tab, as shown in the image below.
Once you click on the Create a new Project tab, it will open the following Create a new Project window. From this window, select C#, All Platforms, and Web from the respective dropdowns as highlighted below. Select ASP.NET Core Web App (Model-View-Controller) as highlighted below, and click the Next button as shown in the image below.
Once you click on the Next button, it will open the Configure Your New Project window. Here, you need to provide the necessary information to create a new ASP.NET Core project. First, give an appropriate name for your project (RoutingInASPDotNetCoreMVC), set the location where you want to create this project, and the solution name for the ASP.NET Core Web application. And finally, click on the Create button, as shown in the image below.
Once you click on the Next button, it will open the following Additional Information window. Here, you need to select Framework – .NET 6.0 (Long-term support), Authentication type – None. You also need to check the Configure for HTTPS and Do not use top-level statements check boxes, and finally, click on the Create button as shown in the below image.
Once you click on the Create Button, the project is going to be created with the Model-View-Controller template with the following folder and file structure.
Understanding the Default Route in ASP.NET Core MVC Web Application:
As we created the project with a Model-View-Controller template, the required MVC Services and MVC Middleware components are, by default, added to the Request Processing Pipeline. So, if you open the Program class, then you will find the following code.
namespace RoutingInASPDotNetCoreMVC { public class Program { public static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllersWithViews(); var app = builder.Build(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); app.Run(); } } }
As you can see in the above code, MVC services are added by the following statement.
builder.Services.AddControllersWithViews();
MVC Middleware Components are added by using the UseRouting and MapControllerRoute methods. Further, if you notice the MapControllerRoute, then you will see the following.
The default route is created with the following URL Pattern. So, if we don’t specify anything in the URL, then by default, the Index action method of the Home Controller class is going to handle the request.
{controller=Home}/{action=Index}/{id?}
In this example, the MapControllerRoute method is used to define a default route. The pattern parameter specifies the route template, where {controller}, {action}, and {id} are placeholders for route parameters. The name parameter gives the route a name, which can be used for generating URLs. Here’s a breakdown of the placeholders:
- {controller}: Represents the name of the controller class.
- {action}: Represents the action method’s name within the controller.
- {id?}: Represents an optional route parameter called “id”.
With this configuration, an incoming URL like /Home/Index would match the Index action method of the HomeController. Similarly, /Products/Details/5 would match the Details action method of the ProductsController with an id parameter set to 5.
You can customize routing further by adding additional routes, using attribute routing, and applying constraints to route parameters. Attribute routing allows you to define routes directly on your action methods or controllers using attributes, providing more control over how URLs are mapped.
Note: When we create an ASP.NET Core MVC Application using the Model-View-Controller Project template, a default routing also gets configured in the Main method of the Program Class. This default routing is used for mapping URL paths to the controller actions.
Understanding Route Template in ASP.NET Core MVC Application:
As we see, the default route is created with the URL Pattern: {controller=Home}/{action=Index}/{id?}
So, the above default route template will map most URLs with the following pattern.
http://localhost:52190/Home/Details/2
- The first segment path of the URL, i.e., /Home, is mapped to the HomeController. As you can see in the URL, we do not have the word Controller with the first segment path of the URL. But it maps to the HomeController because when ASP.NET Core MVC Framework finds the word /Home as the first segment path of the URL, it internally appends the word Controller.
- The second segment path of the URL, i.e., /Details, is mapped to the Details(int id) action method of the HomeController class.
- The third segment path of the URL, i.e., 2, is mapped to the id parameter of the Details(int id) action method.
As you can see in the default route template {controller=Home}/{action=Index}/{id?}, we have a question mark at the end of the id parameter, which makes the id parameter optional. That means the following two requests now map to the same Details action method of the Home Controller class.
/Home/Details/1
/Home/Details
In the default route template {controller=Home}/{action=Index}/{id?}, the value Home in {controller=Home} is the default value for the Controller. Similarly, the value Index in {action=Index} is the default value for the action method. That means if we navigate to the application’s root URL, as shown below, then that request is going to be handled by the Index action method of the Home Controller class.
http://localhost:52190
The following two URLs are also mapped to the Index action method of the HomeController class.
http://localhost:52190/Home
http://localhost:52190/Home/Index
The default route works fine for most of the ASP.NET Core MVC Web Applications. For example, create a controller with the name as StudentController and then copy and paste the following code into it.
using Microsoft.AspNetCore.Mvc; namespace RoutingInASPDotNetCoreMVC.Controllers { public class StudentController : Controller { public string Index() { return "Index() Action Method of StudentController"; } public string Details(int? id) { return $"Details({id}) Action Method of StudentController"; } } }
Now, the URL /student/index is mapped to the Index() action method of the StudentController class, and the URL /student/details or /student/details/5 both are mapped to the Details(int? id) action method of the StudentController.
Can we Configure Multiple Conventional Based Routing in ASP.NET Core MVC Application?
Yes, we can configure Multiple Conventional Based Routes in ASP.NET Core MVC Application. To do this, we need to use the MapControllerRoute method multiple times within the Main method of our Program class. For example, we want to access the Index Action Method of the Student Controller using the following URL.
https://localhost:44359/Student/All
To achieve this, we can configure the MapControllerRoute method, as shown in the below image. Here, you can see we have specified the pattern as Student/All and specified the default controller and action name as controller = Student, action = Index.
Next, we want to access the Details Action Method of the Student Controller using the following URL.
https://localhost:44359/StudentDetails/10
To achieve this, we can configure another MapControllerRoute method, as shown in the below image. Here, you can see we have specified the pattern as StudentDetails/{ID} and specified the default controller and action name as controller = Student”, action = Details.
For the rest of the controller and actions, we need to access them using the following URL Pattern. Along with we also need to configure the default controller and action name as Home and Index.
https://localhost:44359/{Controller Name}/{Action method Name}
To achieve this, we can configure another MapControllerRoute method, as shown in the below image. Here, you can see we have specified the pattern as {controller}/{action}/{id:int?} and specified the default controller and action name as controller = Home, action = Index.
The complete code of the Program class is given below.
namespace RoutingInASPDotNetCoreMVC { public class Program { public static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllersWithViews(); var app = builder.Build(); // Configure the HTTP request pipeline. if (!app.Environment.IsDevelopment()) { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); //https://localhost:44359/Student/All app.MapControllerRoute( name: "StudentAll", pattern: "Student/All", defaults: new { controller = "Student", action = "Index" } ); //https://localhost:44359/StudentDetails/10 app.MapControllerRoute( name: "StudentIndex", pattern: "StudentDetails/{ID}", defaults: new { controller = "Student", action = "Details" } ); //For Rest of the Controller Actions including the Default Home Controller Index app.MapControllerRoute( name: "default", pattern: "{controller}/{action}/{id:int?}", defaults: new { controller = "Home", action = "Index" } ); app.Run(); } } }
With the above changes in place, run the application and navigate to the specific URLs, and you will get the data as expected.
Routing in ASP.NET Core MVC is a fundamental concept that allows you to define how incoming HTTP requests are matched to controller actions and endpoints in your application. It determines how URLs are mapped to specific code that handles the requested functionality. In ASP.NET Core MVC, routing is configured in the Program.cs file of your application. The primary components of routing include:
- Route Template: A route template is a string pattern defining a URL’s structure. It contains placeholders for route parameters that will be extracted from the URL and used as inputs to the associated action method.
- Route Constraints: Constraints are used to specify restrictions on the values of route parameters. For example, you can use constraints to ensure that a parameter matches a specific data type or meets certain conditions.
- Route Data: Route data is information extracted from the URL based on the route template. It includes route parameters and any additional data associated with the route.
Keep in mind that routing is a critical part of building ASP.NET Core MVC applications, as it defines the structure and flow of your application’s URLs and how they correspond to the underlying code.
Conventional-based routing offers simplicity and ease of use, especially for small to medium-sized applications with naming conventions matching the desired URL structure. It allows you to get started without explicit routing configuration quickly. However, for more complex scenarios or when you require more fine-grained control over your URLs, you might choose to use attribute routing or a combination of both attribute and conventional-based routing in your ASP.NET Core MVC application.
In the next article, I am going to discuss how to define the Custom Route and Route Constraints, Optional Parameters, and Default Values in the ASP.NET Core MVC application. In this article, I explain the fundamental of Routing in ASP.NET Core MVC Applications. I hope you enjoy this article.
About the Author:
Pranaya Rout has published more than 3,000 articles in his 11-year career. Pranaya Rout has very good experience with Microsoft Technologies, Including C#, VB, ASP.NET MVC, ASP.NET Web API, EF, EF Core, ADO.NET, LINQ, SQL Server, MYSQL, Oracle, ASP.NET Core, Cloud Computing, Microservices, Design Patterns and still learning new technologies.
Very nice tutorial
“The second segment path of the URL i.e. “/Details” is mapped to the “Details(int id)” action method of the HomeController” – This is not Home controller, but Student controller.
In asp.net 3, to use app.UseMvcWithDefaultRoute we need to disable endpoint routing.
We have updated the article to .NET 6.
thank lot u
Perfectly explained with screen shots amazing.