Adding Constraints to Route Parameters
Introduction
Welcome back! So far, you've covered the basics of routing in ASP.NET Core, including working with parameters, literal segments, and using optional and default values. In this lesson, you'll delve into applying constraints to route parameters. These constraints help ensure that only specific values pass through your routes, increasing the robustness and reliability of your applications.
Understanding Route Constraints
In large applications with numerous routes, it's common for routes to become ambiguous. For example, consider a route like /blog/{year=2024}/{slug?}. This route does not prevent ambiguities because both /blog/2023 (a valid year) and /blog/article-title (a slug) can match.
To solve this, you can define constraints for route parameters to ensure that only specific values pass through your routes. For instance, you can define a constraint to ensure year must be an integer greater than or equal to 2000: /blog/{year:int:min(2000)}/{slug?}.
With this constraint, requests like /blog/article-title will no longer be mistaken for a valid year parameter and will not match this route unless article-title is a valid year. This constraint ensures that only valid years and string slugs are processed correctly, thereby eliminating ambiguities.
Route Constraints Overview
Below you can see all route constraints available in ASP.NET Core:
| Constraint | Description | Matching Values |
|---|---|---|
{id:int} | Ensures the parameter is an integer. | 1, 123, -456 |
{id:guid} | Ensures the parameter is a GUID. | 123e4567-e89b-12d3-a456-426614174000 |
{id:decimal} | Ensures the parameter is a decimal. | 1.23, 45.67, -89.01 |
{id:min(10)} | Ensures the parameter is at least 10. | 10, 11, 999 |
{id:length(6)} | Ensures the parameter is exactly 6 chars. | abcdef, 123456 |
It's also possible to combine multiple constraints by separating them with colons, like so: id:int:min(10)
Route Constraints in Action
