skip to content

In ASP.NET Core, why does an endpoint mapped to /books/{id:int} answer 404 rather than 400 for /books/abc, and what are route constraints really for?

level: middleimportance: must knowfreq 60%

answer

  1. constraints run during matching
  2. no candidate left means no endpoint
  3. disambiguate, don't validate
  4. {id:int:min(1)} chains constraints
  5. invariant culture, values stay strings

basics

~20 s

An inline constraint like :int is checked while routing matches the URL, so a failing value removes the endpoint from the candidates; with nothing selected the request ends as 404. Constraints exist to tell similar routes apart, not to validate input.

solid answer

~40 s

Route constraints such as `int`, `guid`, `range(1,5)`, `minlength(3)` or `alpha` are evaluated by the routing middleware while it selects an endpoint. If `abc` fails `{id:int}`, that endpoint simply is not a candidate, no endpoint is selected, nothing handles the request and the response is 404. Your handler never runs, so it cannot return a helpful 400. Without the constraint, `/books/{id}` with an `int id` parameter would match, binding would fail, and a Minimal API returns 400 (an `[ApiController]` returns a validation ProblemDetails). The docs put it bluntly: don't use constraints for input validation; use them to disambiguate similar routes, such as `/books/{id:int}` beside `/books/{slug}`, where a number reaches one endpoint and a slug the other.

code

csharp · 14 lines
csharp
var app = WebApplication.CreateBuilder(args).Build();

// GET /books/42          -> "book #42"
// GET /books/the-hobbit  -> "book 'the-hobbit'"
app.MapGet("/books/{id:int:min(1)}", (int id) => $"book #{id}");
app.MapGet("/books/{slug}", (string slug) => $"book '{slug}'");

// GET /reviews/abc -> 404: the int constraint fails, no endpoint is selected
app.MapGet("/reviews/{id:int}", (int id) => $"review #{id}");

// GET /authors/abc -> 400: the endpoint matches, binding int id fails
app.MapGet("/authors/{id}", (int id) => $"author #{id}");

app.Run();

go deeper

for a junior

Recall the syntax {id:int} and a few built-ins such as int, guid, range and minlength, and that a failing constraint gives 404.

for a middle

Explain that constraints run during endpoint selection, why that makes the result 404, and how the same request becomes a 400 when only binding fails.

for a senior

Use constraints to separate overlapping routes like /books/{id:int} and /books/{slug}, keep business rules in validation, and spot APIs whose clients cannot tell a bad value from a missing resource.

for a principal

Set the API convention: 404 means no such address, 400 means a bad value, and route constraints only encode the first so error semantics stay consistent across teams.

## Where constraints run An **inline route constraint** is written after a colon inside a parameter: `{id:int}`, `{isbn:length(13)}`, `{rating:range(1,5)}`. Several can be chained, as in `{id:int:min(1)}`. When routing builds its matcher, it turns each name into an `IRouteConstraint` instance by looking the name up in `RouteOptions.ConstraintMap`. At request time the **routing middleware** (`UseRouting`, added for you by `WebApplication`) collects every endpoint whose template matches the path, then asks each constraint whether the captured value is acceptable. An endpoint whose constraint says no is **dropped from the candidate set**. Constraints are part of *matching*, not part of *executing* the endpoint. ## Why the result is 404 Follow `GET /books/abc` against `app.MapGet("/books/{id:int}", ...)`: 1. The path `/books/abc` fits the shape `books/{id}`, so the endpoint is a candidate. 2. `IntRouteConstraint` tries `int.TryParse("abc", NumberStyles.Integer, CultureInfo.InvariantCulture, ...)` and returns `false`. 3. No candidate is left, so routing selects **no endpoint**. 4. The endpoint middleware has nothing to run, the request falls off the end of the pipeline, and the server answers **404 Not Found**. Nothing in your code ran, so there was no chance to explain *what* was wrong. From the client's point of view the resource simply does not exist. Compare the same endpoint **without** the constraint: | Template and handler | `GET /books/abc` | Who decides | |---|---|---| | `/books/{id:int}` with `int id` | 404 | routing: no endpoint matched | | `/books/{id}` with `int id` (Minimal API) | 400 | parameter binding fails to parse `id` | | `[HttpGet("{id}")]` with `int id` on an `[ApiController]` | 400 with a validation `ProblemDetails` body | model binding records a `ModelState` error | ## What constraints are for The ASP.NET Core docs carry a warning in exactly these terms: **don't use constraints for input validation**; invalid input should produce a 400 with an error message, and "route constraints are used to disambiguate similar routes, not to validate the inputs for a particular route." A bookshop is the textbook case: ```csharp app.MapGet("/books/{id:int}", (int id) => $"book #{id}"); app.MapGet("/books/{slug}", (string slug) => $"book '{slug}'"); ``` - `/books/42` matches both shapes, and routing prefers the constrained template, so the id endpoint runs. - `/books/the-hobbit` fails `int`, so only the slug endpoint is left. Without the constraint the two templates would tie on every request. How routing ranks the remaining candidates is a matter of route precedence; the constraint's job is to decide which ones remain. ## The built-in constraints The default `ConstraintMap` in ASP.NET Core 10 registers: - **Type checks:** `int`, `long`, `bool`, `datetime`, `decimal`, `double`, `float`, `guid`. - **Length checks:** `minlength(n)`, `maxlength(n)`, `length(n)` and `length(min,max)`. - **Numeric ranges:** `min(n)`, `max(n)`, `range(min,max)`. - **Text shape:** `alpha` (ASCII letters only) and `regex(expression)`. - **File names:** `file` and `nonfile`, for paths whose last segment does or does not look like `name.ext`. - **Link generation:** `required`, which insists on an explicit (not ambient) value when a URL is generated. Two details trip people up. Type constraints parse with the **invariant culture**, because URLs are not localized. And a constraint only *checks*; it does not convert. `{price:decimal}` still stores the string `"9.99"` in the route values, and binding performs the conversion afterwards. ## Constraints outside the template Inline syntax is the common form, but not the only one. `MapControllerRoute` takes a `constraints` object, as in `app.MapControllerRoute("isbn", "books/{isbn}", new { controller = "Books", action = "ByIsbn" }, new { isbn = @"^\d{13}$" })`. There, a string value is treated as a **regular expression**, whereas an unknown name written inline in a template is not treated as a regex: routing fails with "The constraint reference ... could not be resolved to a type". Either way the constraint behaves the same at request time: a failing value removes the route from the candidates. ## When a 404 is the right answer A constraint that rejects garbage is not always wrong. If `/books/abc` genuinely cannot be any book because ids are numeric and no slug endpoint exists, 404 is honest. The trouble starts when a constraint encodes a *business* rule, such as `range(1,5)` on a review rating that a client submits: the client gets 404 for an out-of-range rating and cannot tell a typo in the URL from a bad value. That rule belongs in validation, which can return a 400 naming the field. ## What interviewers listen for - Constraints are evaluated **during endpoint selection**, so failure means "no endpoint", hence 404. - The handler or action never runs, so it cannot shape the error. - Constraints **disambiguate** overlapping templates; validation belongs after binding. - Constraints use the invariant culture and leave route values as strings.

  • Do the built-in type constraints such as {price:decimal} change the value stored in RouteValues?
    No. The constraint only checks that the string parses, using the invariant culture. `RouteValues["price"]` still holds the string, and model or parameter binding converts it to `decimal` later. That is why a constraint and a binder can disagree only in edge cases such as culture, and why constraints never replace binding.
  • When is a 404 from a failed route constraint acceptable rather than a smell?
    When the value could never identify a resource at that address: a non-numeric id where ids are integers and no other endpoint accepts that shape. It becomes a smell when the constraint enforces a business rule, like a rating range or a minimum length on user input, because the client gets "not found" instead of a 400 that names the bad field.
  • Can you apply more than one constraint to the same parameter?
    Yes, by chaining them with colons: `{id:int:min(1)}` requires an integer of at least 1, and every constraint must pass for the endpoint to stay a candidate. Constraints can also be passed outside the template, for example in the `constraints` argument of `MapControllerRoute`, where string values are treated as regular expressions.

  • Says a failed {id:int} constraint makes ASP.NET Core return 400 Bad Request.
  • Uses range(1,5) on a submitted rating as the endpoint's input validation.
  • Believes the int constraint converts the route value so RouteValues holds an int.
  • Thinks the handler runs and can return a friendly error when a constraint fails.
  • Assumes constraints parse numbers and dates with the server's current culture.