In this article, I am going to discuss Custom Routing in the ASP.NET Core MVC application. Please read our previous article before proceeding to this article where we discussed the basics of Routing as well as we also discussed the fundamentals of Conventional based routing in ASP.NET Core MVC Application. As part of this article, we are going to discuss the following pointers in detail.
Custom Routing in ASP.NET Core MVC Application:
If you want to define your own route then you need to the UseMvc middleware instead of UseMvcWithDefaultRoute(). Within the Configure method of the Startup class file use the UseMVC middleware and within that middleware make a call to the MapRoute method to define your own route as shown in the below image.
The above example is the simplest possible convention-based route for an ASP.NET Core MVC application. Now run the application and navigates to the following URLs and you will see the output as expected.
http://localhost:52190/Student/Details
http://localhost:52190/Student/Index
This is working fine. However, what if we wanted to have more specific routes? Say, something like:
http://localhost:52190/Student/Details/20
http://localhost:52190/Student/Index/10
If you want your controller action methods to match the above URLs, then you need to use a feature called Route Constraints in ASP.NET Core MVC Application.
Route Constraints in ASP.NET Core MVC Application:
Let’s say we want to create a route that will match the following URL.
http://localhost:52190/Student/Index/10
http://localhost:52190/Student/Details/20
In order to achieve this, one of the simplest ways is to define a route as shown below:
Now modify the StudentController as shown below.
The problem with the above route is that it can accept any type of values. Here instead of an integer, if you pass string values then also it accepts and executes the action methods as shown below.
http://localhost:52190/Student/Details/ABC
If you want to restrict the id parameter value to be an integer only, then you need to use a concept called route constraint as shown below:
With the above changes, now run the application and navigate to the following URL and you will see a 404 error. This is because here we are passing the Id parameter value as ABC.
http://localhost:52190/Student/Details/ABC
http://localhost:52190/Student/index/ABC
Now pass the id parameter value as an integer and you should get the output as expected. There are many route constraints are available that you can use. Some of them are as follows.
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/routing?view=aspnetcore-2.2#route-constraint-reference
Optional Parameters:
Before understanding the Optional Parameters, let us first change the StudentController as shown below.
http://localhost:52190/Student/Details
http://localhost:52190/Student/Details/10
In order to achieve this, we need to use optional parameters in our convention-based routes by adding a question mark “?” to the optional parameter’s constraint as shown below.
Providing Default Route Values in ASP.NET Core MVC Application:
Using Default values we can specify what happens if parts of the route are not provided in the URL. For example, when we navigate to the following two URLs
http://localhost:52190/
http://localhost:52190/Home
We want to map the above two URLs to the Home Controller and Index action method of the Application. In order to achieve this, we need to provide default route values while defining the routes as shown below.
Modify the Home Controller as shown below.
http://localhost:52190/
http://localhost:52190/Home
You can also map the default values by using the defaults property as shown below.
Summary:
I hope this post will be helpful to understand the concept of Custom Routing in ASP.NET Core MVC
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
- Creating Custom Routing in ASP.NET Core MVC Application.
- Understanding Route Constraints?
- How to define Optional Parameters in Route?
- Providing Default Route Values.
Custom Routing in ASP.NET Core MVC Application:
If you want to define your own route then you need to the UseMvc middleware instead of UseMvcWithDefaultRoute(). Within the Configure method of the Startup class file use the UseMVC middleware and within that middleware make a call to the MapRoute method to define your own route as shown in the below image.
The above example is the simplest possible convention-based route for an ASP.NET Core MVC application. Now run the application and navigates to the following URLs and you will see the output as expected.
http://localhost:52190/Student/Details
http://localhost:52190/Student/Index
This is working fine. However, what if we wanted to have more specific routes? Say, something like:
http://localhost:52190/Student/Details/20
http://localhost:52190/Student/Index/10
If you want your controller action methods to match the above URLs, then you need to use a feature called Route Constraints in ASP.NET Core MVC Application.
Route Constraints in ASP.NET Core MVC Application:
Let’s say we want to create a route that will match the following URL.
http://localhost:52190/Student/Index/10
http://localhost:52190/Student/Details/20
In order to achieve this, one of the simplest ways is to define a route as shown below:
Now modify the StudentController as shown below.
using Microsoft.AspNetCore.Mvc; namespace FirstCoreMVCApplication.Controllers { public class StudentController : Controller { public string Index(string count) { return "Index() Action Method of StudentController"; } public string Details(string id) { return "Details() Action Method of StudentController"; } } }Now run the application and navigate to the respective URLs and you will see that methods are executed as expected.
The problem with the above route is that it can accept any type of values. Here instead of an integer, if you pass string values then also it accepts and executes the action methods as shown below.
http://localhost:52190/Student/Details/ABC
If you want to restrict the id parameter value to be an integer only, then you need to use a concept called route constraint as shown below:
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; namespace FirstCoreMVCApplication { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseMvc(routes => { routes.MapRoute( name:"default", template: "{controller}/{action}/{id:int}"); }); } } }Note: The {id: int} in the template section specifies that whatever is in this part of the URL must be an integer, otherwise the URL does not map to this route.
With the above changes, now run the application and navigate to the following URL and you will see a 404 error. This is because here we are passing the Id parameter value as ABC.
http://localhost:52190/Student/Details/ABC
http://localhost:52190/Student/index/ABC
Now pass the id parameter value as an integer and you should get the output as expected. There are many route constraints are available that you can use. Some of them are as follows.
- Int
- Bool
- Datetime
- Decimal
- Guid
- length(min,max)
- alpha
- range(min,max)
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/routing?view=aspnetcore-2.2#route-constraint-reference
Optional Parameters:
Before understanding the Optional Parameters, let us first change the StudentController as shown below.
using Microsoft.AspNetCore.Mvc; namespace FirstCoreMVCApplication.Controllers { public class StudentController : Controller { public string Index() { return "Index() Action Method of StudentController"; } public string Details(string id) { return "Details() Action Method of StudentController"; } } }As you can see, the Index action method does not take any parameter while the Details action method takes one parameter. Now we need to invoke the Index action method without parameter. On the other hand, we need to make the id parameter of the Details action method as optional. It means the Details action method should be invoked using the following two URLs.
http://localhost:52190/Student/Details
http://localhost:52190/Student/Details/10
In order to achieve this, we need to use optional parameters in our convention-based routes by adding a question mark “?” to the optional parameter’s constraint as shown below.
using FirstCoreMVCApplication.Models; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; namespace FirstCoreMVCApplication { public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseMvc(routes => { routes.MapRoute( name:"default", template: "{controller}/{action}/{id:int?}"); }); } } }Note: You can define only one optional parameter per route, and that optional parameter must be the last parameter.
Providing Default Route Values in ASP.NET Core MVC Application:
Using Default values we can specify what happens if parts of the route are not provided in the URL. For example, when we navigate to the following two URLs
http://localhost:52190/
http://localhost:52190/Home
We want to map the above two URLs to the Home Controller and Index action method of the Application. In order to achieve this, we need to provide default route values while defining the routes as shown below.
Modify the Home Controller as shown below.
public class HomeController: Controller { public string Index() { return "Index() Action Method of HomeController"; } }Now run the application and navigate to the following URLs and you will see the output as expected.
http://localhost:52190/
http://localhost:52190/Home
You can also map the default values by using the defaults property as shown below.
public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller}/{action}/{id:int?}", defaults: new { controller = "Home", action = "Index" }); }); } }In the next article, I am going to discuss Attribute Routing in ASP.NET Core MVC Application. Here, in this article, I try to explain the Custom Routing in ASP.NET Core MVC Application with an example. I hope you enjoy this article.
Summary:
I hope this post will be helpful to understand the concept of Custom Routing in ASP.NET Core MVC
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
0 comments:
Post a Comment
If you like this website, please share with your friends on Facebook, Twitter, LinkedIn.