What is Routing in ASP.NET Core MVC?
Routing is the process through which the application matches an incoming URL path and executes the corresponding action methods. ASP.NET Core MVC uses a routing middleware to match the URLs of incoming requests and map them to specific action methods.
So, the ASP.NET Core Framework maps the incoming Requests i.e. URLs to the Controllers 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, message handlers, etc.
There are two types of routing for action methods:
- Conventional Routing
- Attribute Routing
In Conventional Based Routing, the route is determined based on the conventions defined in the route templates which will map the incoming Requests (i.e. URLs) to controllers and their action methods. In ASP.NET Core MVC application, the Convention based Routes are defined within the Configure method of the Startup.cs class file.
In Attribute-Based Routing, the route is determined based on the attributes which are configured either at the controller level or at the action method level. We can use both Conventional Based Routing and Attribute-Based Routing in a single application.
Understanding the Default Route in ASP.NET Core MVC Application:
We can add the required MVC middleware into the request processing pipeline either by calling the UseMvcWithDefaultRoute() method or by calling the UseMvc() method within in the Configure() method of the Startup.cs class file as shown in the below code. As of now, we are using the UseMvcWithDefaultRoute() middleware.
public void Configure(IApplicationBuilder app) {
app.UseDeveloperExceptionPage();
app.UseFileServer();
app.UseMvcWithDefaultRoute();
}
Let us have a look at the implementation of the UseMvcWithDefaultRoute() method by visiting the following GitHub URL.
As you can see in the above implementation, this method internally calls the UseMvc() method which will add the default route into the application’s request processing pipeline.
Understanding The Route Template:
The above default route template maps most URLs that have the following pattern.
http://localhost:52190/Student/Details/2
http://localhost:52190/Student/Details
This gives us a default routing rule that allows us to get to the HomeController. Instead of using the UseMvcWithDefaultRoute, let us use the UseMvc, and then configure the route at this point using a named method ConfigureRoute. The following is the implementation of the Startup.cs file.
public void ConfigureServices(IServiceCollection services) {
services.AddMvc();
}
// This method gets called by the runtime.
// Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app) {
app.UseDeveloperExceptionPage();
app.UseFileServer();
app.UseMvc(ConfigureRoute);
}
private void ConfigureRoute(IRouteBuilder routeBuilder) {
//Home/Index
routeBuilder.MapRoute("Default", "{controller = Home}/{action = Index}/{id?}");
}
Inside the ConfigureRoute method, you can configure your routes; you can see that this method has to take a parameter of type IRouteBuilder. The goal of routing is to describe the rules that ASP.NET Core MVC will use to process an HTTP request and find a controller that can respond to that request.
When using attribute-based routing you would mention route on your controller or the action method. You can define multiple routes for the same action method. Here is an example that illustrates this.
public class HomeController : Controller
{
[Route("")]
[Route("Home")]
[Route("Home/Index")]
public IActionResult Index()
{
return View();
}
[Route("Home/GetAuthor/{id:int}")]
public IActionResult GetAuthor(int id)
{
ViewBag.Id = id;
return View();
}
}
Use endpoint routing in ASP.NET Core 3.0 MVC
Endpoint routing is a feature newly introduced in ASP.NET Core 3.0 that enables you to provide routing information to middleware in the request processing pipeline.
Before the introduction of endpoint routing, routing resolution in ASP.NET Core MVC was performed at the end of the request processing pipeline. As a result, route information (such as which action method needs to be executed) was unknown to any middleware processing a request before the MVC middleware in the request processing pipeline.
Route definitions in ASP.NET Core 3.0 MVC
When you create a new ASP.NET Core 3.0 MVC application, a default route will be created for you by Visual Studio. This is how it would look.
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
}
The route definition shown here consists of two parameters — the name of the route and the route pattern. This route will match the following URLs.
/Home/Index
/Author/Index
/Author/Index/12
Note that the UseRouting middleware should be configured ahead of all other middleware including authentication, authorization, and any custom middleware. By contrast, the UseEndpoints middleware should be configured at the end. The following code snippet illustrates this.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Author}/{action=GetAuthor}/{id?}");
});
}
Inside the call to UseEndpoints, MapControllerRoute is used to create a single route. The single route is named default route. Most apps with controllers and views use a route template similar to the default route. REST APIs should use attribute routing.
Multiple conventional routes
Multiple conventional routes can be added inside UseEndpoints by adding more calls to MapControllerRoute and MapAreaControllerRoute. Doing so allows defining multiple conventions, or to adding conventional routes that are dedicated to a specific action, such as:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(name: "blog",
pattern: "blog/{*article}",
defaults: new { controller = "Blog", action = "Article" });
endpoints.MapControllerRoute(name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
The blog route in the preceding code is a dedicated conventional route.
Important:
Routing is configured using the UseRouting and UseEndpoints middleware. To use controllers:
- Call MapControllers inside UseEndpoints to map attribute routed controllers.
- Call MapControllerRoute or MapAreaControllerRoute, to map both conventionally routed controllers and attribute routed controllers.
Refrence: https://dotnettutorials.net, https://www.infoworld.com, https://docs.microsoft.com