Loading

ASP.NET Core

What is Custom Routing in ASP.NET Core MVC?. The Complete ASP.NET Core Developer Course 2023 [Videos].

A custom route constraint can also be used with a Convention based routing. The new version MVC has an override version MapRoute method that accepts a constraint as a parameter. Using this method we can pass over a custom constraint.

Custom Routing in ASP.NET Core MVC Application

In this Video, I am going to discuss Custom Routing in the ASP.NET Core MVC application. Please read our previous Video before proceeding to this Video where we discussed the basics of Routing as well as we also discussed the fundamental of Application. As part of this Video, we are going to discuss the following pointers in detail.

  1. Creating Custom Routing in ASP.NET Core MVC Application.
  2. Understanding Route Constraints?
  3. How to define Optional Parameters in Route?
  4. Providing Default Route Values.

Note: We are going to work with the same example that we created in our previous Video.

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.

Custom Routing in ASP.NET Core MVC Application

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:

Route Constraints in ASP.NET Core MVC Application

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.

  1. Int
  2. Bool
  3. Datetime
  4. Decimal
  5. Guid
  6. length(min,max)
  7. alpha
  8. range(min,max)

For the list of all available route constraints, please find the following MSDN Article.

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.

Providing Default Route Values in ASP.NET Core MVC Application

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" });
});
}
}


See All

Comments (246 Comments)

Submit Your Comment

See All Posts

Related Posts

ASP.NET Core / Blog

What is ASP.NET Core?

ASP.NET Core is the new version of the ASP.NET web framework mainly targeted to run on .NET Core platform.
27-jan-2022 /16 /246

ASP.NET Core / Blog

What is ASP.NET Core Framework?

ASP.NET Core is a cross-platform, high-performance, open-source framework for building modern, cloud-enabled, Internet-connected apps. With ASP.NET Core, you can: Build web apps and services, Internet of Things (IoT) apps, and mobile backends. Use your favorite development tools on Windows, macOS, and Linux.
27-jan-2022 /16 /246

ASP.NET Core / Blog

How to Setup ASP.NET Core Environment ?

ASP.NET Core is a cross-platform, high-performance, open-source framework for building modern, cloud-enabled, Internet-connected apps. With ASP.NET Core, you can: Build web apps and services, Internet of Things (IoT) apps, and mobile backends. Use your favorite development tools on Windows, macOS, and Linux.
27-jan-2022 /16 /246