13Mar 2021 by ganesh
Routing Techniques In ASP.NET CORE
In this tutorials will discuss and understand how routing is worked in asp.net core.
Routing
Routing in ASP.NET Core is the process of mapping incoming requests to application logic that are resides in controllers and methods.
ASP.NET Core maps the incoming request based on the routes that you configure in your application, and for each route, you can set specific configurations, such as default values, message handlers, constraints
Routing Techniques
Conventional routing: The route is determined based on conventions that are defined in route templates, at run time, it will will map requests to the controllers and actions or methods.
Attribute-based routing: The route is determined based on attributes that you set on your controllers and methods.
Routing Process
When a request came from the browser at our application, the controller in the MVC handles the incoming http request and responds to the user action. The incoming request URL is mapped to a controller action method. This mapping is done by the routing rules defined in our application.
If URL is not matched it return as page not found as response.
For example, when a request is issued to /Home/Index, this URL is mapped to the Index() action method in the HomeController class
Similarly, when a request is issued to /Home/Details/1, this URL is mapped to the Details() action method in the HomeController class. The value 1 in the URL is automatically mapped to the “id” parameter of the Details(int id) action method.
UseMvcWithDefaultRoute: The following is the code in the Configure() method in Startup.cs file. The code in this method sets up the HTTP request processing pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseMvcWithDefaultRoute();
}
UseMvc or UseMvcWithDefaultRoute
If you want to define your own route templates and want to have more control over the routes, use UseMvc() method, instead of UseMvcWithDefaultRoute() method. For ex.
- Changes Default action to about instead of index.
- Configure multiple routes
app.UseMvc(
routes => {
routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}");
});
You can watch our video version of this tutorials with step by step explanation.