Routing in ASP.NET Core MVC is the process of mapping incoming HTTP requests to the appropriate controller actions. It allows you to define URL patterns that your application can respond to. This ensures that users and search engines can access your application's content in a structured and user-friendly way.
ASP.NET Core MVC uses a routing table to match request URLs against defined routes. When a request arrives, the routing engine iterates through the registered routes, attempting to find a match. The first route that successfully matches the request is used to determine the controller and action to execute.
Route templates are the core of defining how URLs are mapped. They are strings that define URL patterns, including literal segments and placeholders (parameters).
{controller}/{action}/{id?}
In the example above:
{controller}: A placeholder for the controller name.{action}: A placeholder for the action method name.{id?}: An optional placeholder for an identifier. The '?' makes it optional.
Routes are typically configured in the Configure method of the Startup.cs file (or Program.cs in .NET 6+ minimal APIs).
You can use either convention-based routing or attribute routing.
Convention-based routing defines a default route template for the application.
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
This configuration sets up a default route where if no controller or action is specified, it defaults to the "Home" controller and its "Index" action.
Attribute routing allows you to define routes directly on your controllers and action methods using attributes.
// Controller
[Route("api/[controller]")]
public class ProductsController : Controller
{
// Action
[HttpGet("{id}")]
public IActionResult GetProduct(int id)
{
// ... implementation
return Ok($"Product ID: {id}");
}
}
The [Route(...)] attribute on the controller defines a base route,
and [HttpGet(...)] defines specific routes for actions.
You can apply constraints to route parameters to ensure they match specific criteria.
app.MapControllerRoute(
name: "product",
pattern: "products/{productId:int}", // productId must be an integer
defaults: new { controller = "Products", action = "Details" });
Common constraints include int, alpha, guid, minLength, maxLength, and custom regular expressions.
The current request path is /msdn/learn/aspnet-core/mvc/routing.
Based on common routing conventions, this path might map to a controller named "Msdn" (or similar)
and an action method like "LearnAspnetCoreMvcRouting", or it could be handled by a specific route
configured for documentation paths.