What are the types of routing in ASP.NET MVC?
The procedure of mapping inbound requests to application logic residing in methods and controllers is considered to be routing in ASP.NET Core. It is responsible for incoming mapping requests based on the routes configured by you in your application, and it is possible to set some particular configurations for every route, such as message handlers, default values, constraints, and so forth.
You will come across several ways for controlling routing in the ASP.NET Core application services. Amongst these, the two most common ways happen to be conventional routing and attribute-based routing.
Conventional routing
Once a fresh ASP.net Core MVC application is created by making use of the default template, the app configures a default routing. For this, we will create a project to examine this.
Once you have used the default ASP.net Core MVC template for creating a new project, we will consider looking at the startup.cs class. It is shown that the app has configured the default routing: for C#
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: “default”,
pattern: “{controller=Home}/{action=Index}/{id?}”);
});
We make use of the MapControllerRoute() process for creating a route by providing the name default.
The default route template is configured by MVC as {controller=Home}/{action=Index}/{id?}. This is going to match the Index() method with an optional parameter id in HomeController. It can likewise match a URL path such as /Books/Details/5 and is going to extract the route values by tokenizing the path. MVC will try to find out a controller with the name of BooksController and pass the id parameter as 5 for running the Details() action method.
After running the application, we will be placing a breakpoint in the HomeController’s Index() method. It is found that this process is executed automatically.
Following this, we will modify the default route. For this, we’re going to add a new controller named BooksController with an optional parameter id and an action method Details(). The parameter id happens to be:
public class BooksController : Controller
{
public IActionResult Details(int id)
{
ViewBag.Id = id;
return View();
}
}
Following this, we will be creating a view for the action method Details():
@{
ViewData[“Title”] = “Details”;
int id = ViewBag.Id;
}
<h1>Details</h1>
Book Id : @id
Next, we will be modifying the default route within the startup class:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: “default”,
pattern: “{controller=Books}/{action=Details}/{id?}”);
});
Next, we will run the application again. It is found that the call goes to BooksController’s Details() method by default.
Multiple routes
Multiple routes can be added inside UseEndpoints() simply by calling MapRoute() several times. In this way, we will be capable of defining multiple conventions or adding routes dedicated to a particular action:
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: “blog”,
pattern: “blog/{*article}”,
defaults: new { controller = “Blog”, action = “Article” });
endpoints.MapControllerRoute(
name: “default”,
pattern: “{controller=Books}/{action=Details}/{id?}”);
});
Here, the blog route happens to be a dedicated conventional route that makes use of the traditional routing system. Action and controller will have the default values only since they are not going to appear as parameters in the route template. In this way, the route will be mapping to the BlogController.Article() action method at all times.
It will be a sensible idea to indicate a route name while making the routes. This will provide the route with a logical name that can be used for URL generation.
Attribute routing
It will be possible to use the Attribute Routing feature by placing a route on the action method or the controller.
Here, we will be modifying the Configure() method within the startup.cs class and also get rid of the default routes as well.
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
Next, we will be modifying the BooksController by providing custom attributes as the routes:
public class BooksController : Controller
{
[Route(“”)]
[Route(“Home”)]
[Route(“Home/Index”)]
public IActionResult Index()
{
return View();
}
[Route(“Home/Details/{id:int}”)]
public IActionResult Details(int id)
{
ViewBag.Id = id;
return View();
}
}
Here, the URL paths / have been specified for the Details() method and the BooksController.Index() action. The action method name and the controller name are not going to play any part in figuring out which particular action method to implement while making use of Attribute Routing.
The Http[Verb] attributes are likewise used by us for Attribute Routing:
[HttpGet(“/books”)]
public IActionResult ListBooks()
{
// …
}
[HttpPost(“/books”)]
public IActionResult CreateBook(…)
{
// …
}
MVC will be executing the ListBooks() action for the URL path /books when the HTTP verb happens to be CreateBook() and GET when the HTTP verb happens to be POST.
Multiple routes
Multiple routes reaching the identical action are also supported by attribute routing. The most typical use of this will be to attain the functionality of the default route:
[Route(“[controller]”)]
public class BooksController : Controller
{
[Route(“”)] // Matches ‘Books’
[Route(“Index”)] // Matches ‘Books/Index’
public IActionResult Index()
}
The Index() method is going to match the URL Books/Index as well as /Books by defining the two routes.
Conclusion
ASP.NET Core’s routing infrastructure is quite sophisticated, and there are many more features that have not been covered in this particular article. In case you like to have some more ideas regarding the routing abilities of ASP.net Core, it will be sensible to take a look at the documents at https://docs.microsoft.com/en-us/aspnet/core/fundamentals/routing.