ASP.NET Core Routing
This document provides a comprehensive guide to understanding and implementing routing in ASP.NET Core. Routing is a critical component that maps incoming HTTP requests to the appropriate handler or controller action in your application.
Introduction to Routing
Routing determines how your application responds to a URL request. In ASP.NET Core, routing is highly flexible and can be configured using either convention-based routing or attribute-based routing (or a combination of both).
Core Concepts
Key concepts in ASP.NET Core routing include:
- Endpoints: The fundamental building blocks that represent a handler for an incoming request.
- Route Templates: Patterns that define the structure of URLs your application can match.
- Route Constraints: Rules that limit which requests can match a specific route template.
- Route Values: Data extracted from the URL that can be passed to your handlers.
- Request Delegates: Code that executes when a request is successfully routed.
Route Templates
Route templates are strings that define how URLs are matched and constructed. They can include literal segments and placeholder segments.
A simple route template:
/Products/{id}
In this template:
/Products/
is a literal segment.{id}
is a placeholder segment that captures a value from the URL and makes it available as a route parameter namedid
.
Route Constraints
Route constraints allow you to specify rules for placeholder segments, ensuring that only matching requests are processed by a particular route. For example, you can constrain a segment to only accept digits.
Example using a constraint:
/Products/{id:int}
This route template will only match if the id
segment consists of one or more digits.
Common constraints include:
Constraint | Description |
---|---|
int |
Matches an integer. |
float |
Matches a floating-point number. |
guid |
Matches a GUID. |
alpha |
Matches only alphabetic characters. |
maxLength(n) |
Matches a string with a maximum length of n . |
min(n) |
Matches a number greater than or equal to n . |
Attribute Routing
Attribute routing allows you to define routes directly on your controller actions or classes using attributes. This makes it easier to organize and understand the routing for specific components.
Example using [Route]
attribute:
public class ProductsController : Controller
{
[Route("api/products")]
[HttpGet]
public IActionResult GetAllProducts()
{
// ... implementation
return Ok(new[] { "Product A", "Product B" });
}
[Route("api/products/{id:int}")]
[HttpGet("{id}")] // Inherits base route and adds method-specific route
public IActionResult GetProductById(int id)
{
// ... implementation
return Ok($"Product with ID: {id}");
}
}
The [HttpGet]
, [HttpPost]
, etc., attributes are also part of attribute routing, defining the HTTP method for the route.
Convention Routing
Convention routing defines routes in your application's startup configuration, typically in Program.cs
or Startup.cs
.
Example using MapControllerRoute
:
// In Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews(); // Or AddControllers()
var app = builder.Build();
// ... middleware setup ...
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
This sets up a default route that looks for a controller (defaulting to Home
), an action (defaulting to Index
), and an optional id
parameter.
Route Parameters
Parameters defined in route templates (e.g., {id}
) are available to your controller actions. ASP.NET Core automatically binds these values to matching action parameters.
Route Values
Route values are the data extracted from the URL that match the placeholder segments in a route template. They are crucial for passing data between the URL and your application logic.
Route Generation
ASP.NET Core provides mechanisms to generate URLs based on route names or controller actions. This is essential for creating links in your views or redirecting users.
In Razor views, you can use the Url.Action()
helper:
<a asp-controller="Products" asp-action="GetProductById" asp-route-id="123">View Product 123</a>
Advanced Topics
Explore more advanced routing features:
- Route Order: The order in which routes are defined can matter, especially when templates overlap.
- Route Groups: Grouping related routes, especially with attribute routing, for cleaner definitions.
- Custom Route Constraints: Creating your own constraints for specific validation needs.
- Routing Middleware: Understanding how the routing middleware works within the ASP.NET Core pipeline.
- API Routing: Specific considerations for routing API endpoints.
Mastering routing is key to building robust and scalable ASP.NET Core applications. Refer to the official Microsoft documentation for the most up-to-date and detailed information.