8.5 — Route Constraints¶
← Roadmap · Section: 8. Routing Prev: 8.4 Route templates · Next: 8.6 Link generation
Markers: ⭐ 💻 · Confidence: 🔴 · Last reviewed: —
TL;DR¶
A route constraint restricts what a route parameter will accept — {id:int} matches only if
the segment parses as an integer.
- Their job is disambiguating routes, so
/orders/42and/orders/recentcan go to different actions. - ⚠️ They are not validation. A failed constraint produces a 404, not a helpful error message.
- Write a custom one by implementing
IRouteConstraintand registering it by name.
Definitions¶
| Term | What it is | What it means |
|---|---|---|
| Route constraint | a rule on a parameter | Restricts which values a segment will match. Written {id:int}. |
| Inline constraint | the :name syntax |
The usual form, written directly in the template. |
IRouteConstraint |
an interface | One method, Match. What a custom constraint implements. |
RouteOptions.ConstraintMap |
a dictionary | Maps constraint names to their implementing types. |
| Type constraint | e.g. :int, :guid |
The value must parse as that type. |
| Range constraint | e.g. :min(1), :range(1,100) |
Numeric bounds. |
| Length constraint | e.g. :minlength(3) |
String length bounds. |
:regex(...) |
a constraint | Matches a regular expression. Powerful and easy to misuse. |
:required |
a constraint | The value must be non-empty. Useful with optional parameters. |
:alpha |
a constraint | Letters only, ASCII. |
The concept¶
What they are actually for¶
The obvious reading is "validation" — and that is the wrong mental model.
Their real job is choosing between routes:
[HttpGet("orders/{id:int}")] // /orders/42
public IActionResult GetById(int id) { }
[HttpGet("orders/{status:alpha}")] // /orders/pending
public IActionResult GetByStatus(string status) { }
Without constraints, both templates are orders/{something} and the router cannot tell them
apart — you get an ambiguity error at startup
(8.7). The constraints make the two patterns distinguishable.
A picture: sorting post by the shape of the envelope. A machine that separates letters from parcels is not checking whether the address is valid — it is deciding which chute to send each item down.
⚠️ They are not validation¶
This is the point to be precise about, and it comes up in interviews.
Request /orders/0 and you get:
Not "id must be at least 1". The router simply found no matching endpoint, so from the client's perspective the URL does not exist.
That is fine for disambiguation and useless as an API contract. A caller sending a bad ID gets no idea what they did wrong.
So the rule is:
- Constraint — to distinguish routes, and to reject values that are structurally wrong
(
/orders/abcwhere a GUID is expected) - Validation — for business rules, with a helpful 400 response (11.4)
[HttpGet("orders/{id:guid}")] // structural — 404 for /orders/abc is fine
public async Task<IActionResult> Get(Guid id, CancellationToken ct)
{
// Business rules go here, returning a real message
var order = await _orders.GetAsync(id, ct);
return order is null ? NotFound() : Ok(order);
}
⚠️ A GUID constraint is genuinely useful though, because without it /orders/abc reaches
your action and model binding produces Guid.Empty — a valid GUID that matches nothing, so you
get a confusing "not found" for what was really a malformed request.
How it works¶
The simple version — the built-in set¶
| Constraint | Matches | Example |
|---|---|---|
:int |
An integer | {id:int} |
:long, :float, :double, :decimal |
Those numeric types | {price:decimal} |
:bool |
true or false |
{active:bool} |
:guid |
A GUID | {id:guid} |
:datetime |
A parseable date | {from:datetime} |
:alpha |
ASCII letters only | {code:alpha} |
:minlength(n) / :maxlength(n) |
String length | {slug:minlength(3)} |
:length(n) / :length(min,max) |
Exact or range | {code:length(6)} |
:min(n) / :max(n) / :range(a,b) |
Numeric bounds | {page:int:min(1)} |
:regex(...) |
A pattern | {sku:regex(^[A-Z]{{3}}\\d{{4}}$)} |
:required |
Non-empty | {id:required} |
Constraints chain with colons and all must pass:
Real examples¶
// Distinguish an ID from a keyword
[HttpGet("orders/{id:guid}")] public IActionResult Get(Guid id) { }
[HttpGet("orders/recent")] public IActionResult Recent() { }
// Date segments
[HttpGet("reports/{year:int:range(2000,2100)}/{month:int:range(1,12)}")]
public IActionResult Report(int year, int month) { }
// A fixed-format code
[HttpGet("products/{sku:length(8)}")]
public IActionResult BySku(string sku) { }
⚠️ The regex escaping trap¶
Regex constraints work, and the escaping catches everyone:
// In an attribute — braces must be DOUBLED
[HttpGet("products/{sku:regex(^[[A-Z]]{{3}}\\d{{4}}$)}")]
Two levels of escaping are happening at once. The route template parser treats { and } as
parameter delimiters, so a regex quantifier like {3} must be written {{3}}. Square brackets
need doubling in attribute form too.
The result is unreadable, and unreadable route templates are a maintenance problem.
Prefer a custom constraint for anything non-trivial — it is testable, named, and reusable:
How it actually works — custom constraints¶
Implement IRouteConstraint:
public class SkuRouteConstraint : IRouteConstraint
{
private static readonly Regex Pattern = new(
@"^[A-Z]{3}\d{4}$", RegexOptions.Compiled | RegexOptions.CultureInvariant);
public bool Match(
HttpContext? httpContext,
IRouter? route,
string routeKey,
RouteValueDictionary values,
RouteDirection routeDirection)
{
if (!values.TryGetValue(routeKey, out var value) || value is null)
return false;
var text = Convert.ToString(value, CultureInfo.InvariantCulture);
return text is not null && Pattern.IsMatch(text);
}
}
Register it under a name:
builder.Services.Configure<RouteOptions>(options =>
{
options.ConstraintMap.Add("sku", typeof(SkuRouteConstraint));
});
Then use it:
Three details worth knowing.
RouteDirection tells you whether this is an incoming match or a link being generated
(8.6). Constraints that should only apply one way check it.
Constraints run on every matching attempt, so they must be fast. A compiled regex is fine; a database lookup is not — that belongs in the action.
Constraints are resolved from DI in .NET 7+, so a custom one can take dependencies. Use that sparingly for the same performance reason.
The deeper detail — where constraints run¶
⚠️ Constraints run during routing, which is very early — before authentication, before model binding, before your action.
Two consequences.
They cannot produce a useful error. There is no ModelState, no response shaping, nothing.
Failure means "this endpoint did not match", full stop.
They must not do anything expensive. A constraint runs for every candidate endpoint on every request that reaches that shape. Putting a database call in one multiplies your query load by the number of candidate routes.
⚠️ And :datetime is worth avoiding. It parses using the current culture by default, so
/reports/03-04-2026 means March 4th on one server and April 3rd on another. Use separate
int-constrained segments, or an ISO string parsed explicitly in the action.
Code¶
A realistic controller using constraints for what they are good at:
[ApiController]
[Route("api/[controller]")]
public class ProductsController(IProductService products) : ControllerBase
{
// Disambiguation: a GUID id versus a text slug at the same position
[HttpGet("{id:guid}")]
public async Task<IActionResult> GetById(Guid id, CancellationToken ct)
=> await products.GetAsync(id, ct) is { } p ? Ok(p) : NotFound();
[HttpGet("{slug:minlength(3):maxlength(100)}")]
public async Task<IActionResult> GetBySlug(string slug, CancellationToken ct)
=> await products.GetBySlugAsync(slug, ct) is { } p ? Ok(p) : NotFound();
// A literal beats both of the above — see 8.7
[HttpGet("featured")]
public async Task<IActionResult> Featured(CancellationToken ct)
=> Ok(await products.GetFeaturedAsync(ct));
// Structural constraints only. Business rules are validated properly below.
[HttpGet("category/{categoryId:int:min(1)}")]
public async Task<IActionResult> ByCategory(
int categoryId,
[FromQuery] int pageNumber = 1,
[FromQuery] int pageSize = 20,
CancellationToken ct = default)
{
// Query parameters get REAL validation, with a real message —
// unlike a constraint, which would just 404
if (pageSize is < 1 or > 100)
return BadRequest(new ProblemDetails
{
Status = StatusCodes.Status400BadRequest,
Title = "Invalid page size",
Detail = "pageSize must be between 1 and 100."
});
return Ok(await products.ByCategoryAsync(categoryId, pageNumber, pageSize, ct));
}
}
The contrast in that last action is the point of the note. categoryId is constrained in the
route, so a non-numeric value 404s — acceptable, because it is structurally wrong. pageSize
comes from the query string and is validated properly, so a caller sending 5000 gets a message
explaining the limit rather than a bare 404.
Interview questions¶
Q: What are route constraints for?
Disambiguating routes, primarily. If two actions both match orders/{something}, the router
cannot choose between them and you get an ambiguity error at startup — adding {id:int} to one
and {status:alpha} to the other makes the patterns distinguishable. They also usefully reject
values that are structurally wrong, like a non-GUID where a GUID is expected, which stops the
request reaching your action with a meaningless Guid.Empty.
Q: Are route constraints validation?
No, and treating them as validation is the common mistake. A failed constraint means the endpoint
did not match, so the client gets a bare 404 with no explanation — not a 400 saying what was
wrong. Constraints run during routing, before model binding and before your action, so there is
no ModelState and no way to shape a useful response. Structural checks belong in constraints;
business rules belong in validation, where you can return a ProblemDetails explaining the
problem.
Q: How do you write a custom route constraint?
Implement IRouteConstraint, which has a single Match method receiving the route values and
the constraint's key, returning whether it matches. Then register it in RouteOptions.ConstraintMap
under a name, and use that name inline as {code:sku}. It is worth preferring this over an inline
regex for anything non-trivial, because regex in a route template requires doubling every brace
to escape the parameter delimiters, which makes the template unreadable. A custom constraint is
also testable and reusable.
Q: What should you be careful about with constraints?
Performance, mainly — a constraint runs for every candidate endpoint on every matching attempt, so
anything expensive multiplies with your traffic. A compiled regex is fine; a database lookup is
not, and belongs in the action. The other one is :datetime, which parses using the current
culture, so the same URL means different dates on servers with different locales. I would use
separate integer-constrained segments or parse an ISO string explicitly instead.
Traps ⚠️¶
- A failed constraint gives a 404, not a 400. They are not validation.
- Regex constraints need doubled braces in attributes —
{{3}}for{3}— which makes them unreadable. :datetimeis culture-dependent. The same URL parses differently on different servers.- Constraints run on every candidate endpoint. Anything slow multiplies with traffic.
:alphais ASCII only, so it rejects accented characters and non-Latin scripts.- Constraints run before authentication, so they cannot depend on the current user.
- A constraint runs during link generation too unless it checks
RouteDirection. :intaccepts negative numbers. Add:min(1)if you meant positive.
Related¶
- 8.4 Route templates — where constraints are written
- 8.7 Endpoint precedence — why constraints resolve ambiguity
- 8.6 Link generation —
RouteDirection - 11.4 DataAnnotations — real validation
- 11.5 ModelState — returning a useful 400
- 10.8 ProblemDetails — the error shape
- 1.3 String comparison — culture issues