Conventional routing is the traditional URL mapping system in ASP.NET that uses predefined patterns to determine which controller and action should handle a specific HTTP request.
Conventional routing establishes global rules that apply to the entire application, usually in Program.cs
(or Startup.cs
in earlier versions).
Although minimal APIs and attribute routing are more common in modern projects, you may still encounter conventional routing in large applications or during migrations from earlier versions.
And it’s quite horrible, so if you can avoid using it, that’s better. But just in case you have to, let’s get to it 👇
How does Conventional Routing work?
Conventional routing is based on predictable conventions that follow the standard pattern of {controller}/{action}/{id?}
.
This approach allows ASP.NET to automatically map URLs to the corresponding controllers and actions without the need for additional configuration in each method.
Conventional routes follow a URL pattern with this format:
"{controller=Home}/{action=Index}/{id?}"
This means:
controller
: the name of the controller (default isHome
).action
: the method within the controller (default isIndex
).id?
: optional parameter that can be used as an identifier.
Setting up Conventional Routing
Routing patterns are applied using methods like MapControllerRoute
or MapDefaultControllerRoute
.
Let’s see how conventional routing would be applied with a simple example,
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews(); // Enables MVC
var app = builder.Build();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
public class ProductsController : Controller
{
public IActionResult Details(int id)
{
// Here would go the logic to get the product with that id
return Content($"Displaying product with ID = {id}");
}
}
With this configuration,
- A URL like
/Products/Details/5
will map to theProductsController
- Action
Details
, - The value
5
will be passed as theid
parameter.
Advanced Routing
Of course, just like with attribute routing, it is possible to create more advanced routing systems if needed for our project.
Let’s look at some of them.
Fixed Controller Route
app.MapControllerRoute(
name: "blog",
pattern: "blog/{action}/{id?}",
defaults: new { controller = "Blog" });
Here, any route that starts with /blog
will always be directed to the BlogController
, with the action and id
as dynamic parts.
Route with Multiple Parameters
app.MapControllerRoute(
name: "blogPost",
pattern: "blog/{year}/{month}/{day}",
defaults: new { controller = "Blog", action = "Post" });
A URL like /blog/2023/10/05
will be directed to BlogController.Post(int year, int month, int day)
with the corresponding parameters.