ASP.NET Core Routing
This document provides a comprehensive overview of routing in ASP.NET Core, explaining how requests are mapped to specific actions in your application.
What is Routing?
Routing is the process of determining how an incoming HTTP request is handled by your web application. In ASP.NET Core, routing is a key component that matches incoming request URIs to specific endpoints. This process is primarily handled by the routing middleware.
Routing Concepts
- Route Templates: Define the patterns that incoming URIs are matched against.
- Route Constraints: Specify conditions that must be met for a route to match.
- Route Values: Parameters extracted from the URI or generated for a link.
- Endpoint Routing: The modern routing system in ASP.NET Core, offering more flexibility and performance.
Endpoint Routing
ASP.NET Core uses a convention-based and attribute-based routing system. Endpoint routing is the default and recommended approach.
Convention-based Routing
This is the traditional way of defining routes, typically configured in the Startup.cs (or Program.cs in .NET 6+) file. You define a default route template that applies to your entire application.
// In Startup.cs (Configure method) or Program.cs
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
In this example:
{controller=Home}: Specifies the controller name, defaulting to "Home" if not provided.{action=Index}: Specifies the action method name, defaulting to "Index" if not provided.{id?}: Specifies an optional parameter named "id".
Attribute-based Routing
Attribute-based routing allows you to define routes directly on your controller actions using attributes. This provides more control and can be more readable for complex routing scenarios.
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class ProductsController : ControllerBase
{
[HttpGet] // Matches GET /api/products
public IActionResult GetAll()
{
// ...
}
[HttpGet("{id}")] // Matches GET /api/products/{id}
public IActionResult GetById(int id)
{
// ...
}
[HttpPost] // Matches POST /api/products
public IActionResult Create([FromBody] Product product)
{
// ...
}
}
Route Constraints
Constraints are used to restrict the values that route parameters can accept. They are defined within curly braces in the route template.
| Constraint | Description | Example Template |
|---|---|---|
int |
Matches an integer. | /products/{id:int} |
alpha |
Matches alphabetic characters only. | /users/{username:alpha} |
maxLength |
Matches a string with a maximum length. | /search/{query:maxLength(50)} |
min |
Matches a number greater than or equal to a specified value. | /items/{count:min(1)} |
guid |
Matches a GUID. | /files/{fileId:guid} |
Route Parameters and Values
Route parameters are placeholders in your route template (e.g., {id}). These parameters become available as arguments to your controller actions or as properties on the RouteData object.
Generating URLs
You can use the Url.Action() or LinkGenerator service to generate URLs dynamically, which is crucial for creating links in your views and for API responses.
// In a Razor view
<a asp-controller="Products" asp-action="Details" asp-route-id="123">View Product 123</a>
// In a controller
public IActionResult GetProductLink()
{
var url = Url.Action("Details", "Products", new { id = 456 });
return Ok(url); // Returns a URL like "/Products/Details/456"
}
Important Note on Order
The order in which you configure routes matters. The routing middleware processes routes in the order they are defined. More specific routes should typically be placed before more general routes.
Advanced Routing Features
- Route Groups: Group related routes for cleaner organization.
- Route Aliases: Provide alternative URLs for existing routes.
- Fallback Routes: Handle requests that don't match any defined routes (e.g., for single-page applications).
Tip
When working with APIs, consider using the [Route] attribute on controllers and [HttpGet], [HttpPost], etc., on actions for clear, RESTful routing.