In ASP.NET Core 10, how do you build and register a custom IRouteConstraint that accepts only ISBN-13 book identifiers, and when is regex enough?
answer
- bool Match(... RouteDirection)
- RouteOptions.SetParameterPolicy<T>("isbn13")
- IncomingRequest vs UrlGeneration
- regex: escape braces, anchor ^ $
- CreateSlimBuilder leaves regex unregistered
basics
~10 sImplement IRouteConstraint.Match to read values[routeKey] and run the ISBN-13 checksum, register it with RouteOptions.SetParameterPolicy under a name, then use {isbn:isbn13}. A regex constraint is enough when the shape matters but the checksum does not.
solid answer
~40 sA custom constraint implements `IRouteConstraint`, whose single `Match` method receives the `HttpContext`, the parameter name (`routeKey`), the `RouteValueDictionary` and a `RouteDirection` saying whether routing is matching a request or generating a link. For ISBN-13 you read `values[routeKey]` as a string, check 13 ASCII digits and the weighted 1-3 checksum, and return a bool. You register it in `RouteOptions`, preferably with `SetParameterPolicy<Isbn13RouteConstraint>("isbn13")`, which is trimming-safe, rather than adding to `ConstraintMap`, then write `/books/{isbn:isbn13}`. A built-in `regex(...)` constraint covers the shape, 13 digits starting 978 or 979, without code, but templates need doubled braces and anchors, and `CreateSlimBuilder` apps must register it first. Either way a failing value never reaches the endpoint; it falls through to another route or ends as 404, so use constraints to disambiguate routes, not to report a bad ISBN.
code
csharp · 13 linesvar builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<RouteOptions>(options =>
options.SetParameterPolicy<Isbn13RouteConstraint>("isbn13"));
var app = builder.Build();
// /books/9780261103573 -> by ISBN (checksum passes)
// /books/the-hobbit -> by slug
app.MapGet("/books/{isbn:isbn13}", (string isbn) => $"ISBN {isbn}");
app.MapGet("/books/{slug}", (string slug) => $"slug {slug}");
app.Run();go deeper
Recall that custom constraints implement IRouteConstraint and are registered by name in RouteOptions before use in a template.
Explain the Match parameters, especially routeKey and RouteDirection, and how a regex constraint must escape braces and anchor its pattern.
Decide between a constraint and validation by whether it separates routes, register with SetParameterPolicy for trimmed apps, and remember CreateSlimBuilder's missing regex.
Keep custom constraints rare and shared: a small, reviewed set of named constraints keeps URL contracts consistent and avoids per-team 404 semantics.
## The contract Every constraint, built-in or custom, implements `Microsoft.AspNetCore.Routing.IRouteConstraint`: ```csharp bool Match(HttpContext? httpContext, IRouter? route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection); ``` - `routeKey` is the parameter name the constraint is attached to, such as `isbn`. - `values` holds the route values; on an incoming request the captured value is a **string**. - `routeDirection` is `RouteDirection.IncomingRequest` while routing matches a request and `RouteDirection.UrlGeneration` while `LinkGenerator` or `Url.Action` builds a link. The same constraint runs in both directions, so a link with an invalid ISBN is not generated either. - `httpContext` can be `null` during link generation outside a request, so never dereference it blindly. ## An ISBN-13 constraint for a bookshop An ISBN-13 is 13 digits whose weighted sum, using weights 1 and 3 alternately, is divisible by 10: ```csharp public sealed class Isbn13RouteConstraint : IRouteConstraint { public bool Match(HttpContext? httpContext, IRouter? route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection) { if (!values.TryGetValue(routeKey, out var raw)) return false; var s = Convert.ToString(raw, CultureInfo.InvariantCulture); if (s is null || s.Length != 13) return false; var sum = 0; for (var i = 0; i < 13; i++) { if (!char.IsAsciiDigit(s[i])) return false; sum += (s[i] - '0') * (i % 2 == 0 ? 1 : 3); } return sum % 10 == 0; } } ``` It follows the built-in constraints' habits: invariant-culture conversion, no exceptions for bad input, and no allocation beyond the string it was given. Keep `Match` **cheap and side-effect free**; it may run for every request that reaches the template's shape and again during link generation. ## Registering and using it Constraint names live in `RouteOptions`. Two ways to add one: | API | Notes | |---|---| | `options.SetParameterPolicy<Isbn13RouteConstraint>("isbn13")` | Trimming-safe; preferred for Native AOT or trimmed apps | | `options.ConstraintMap.Add("isbn13", typeof(Isbn13RouteConstraint))` | Works, but the `ConstraintMap` getter is annotated `[RequiresUnreferencedCode]`, so trimming warns | Either goes inside `builder.Services.Configure<RouteOptions>(...)` or `builder.Services.AddRouting(...)`. The template then names it: `app.MapGet("/books/{isbn:isbn13}", ...)`, or `[HttpGet("{isbn:isbn13}")]` on a controller. Routing creates the instance itself: a constraint written as `isbn13(978)` passes `978` to a constructor parameter, and constructor parameters whose type is not `IConvertible` are resolved from the service provider. ## When regex is enough If you only need the **shape**, the built-in `regex` constraint avoids a class: ```csharp app.MapGet(@"/books/{isbn:regex(^97(8|9)\d{{10}}$)}", (string isbn) => isbn); ``` Three traps: 1. **Escaping.** Braces inside a template must be doubled, so the quantifier `{10}` is written `{{10}}`; in a regular C# string every `\` must also be doubled, which is why a verbatim string helps. 2. **Anchoring.** Without `^` and `$` the expression matches any substring, so `abc9780000000000xyz` would pass. 3. **Registration.** `WebApplication.CreateBuilder` calls `AddRouting`, which registers `regex`. `WebApplication.CreateSlimBuilder`, used by the `webapiaot` template, calls `AddRoutingCore`, which leaves a stub: the first time routing creates the constraint it throws `InvalidOperationException` telling you to call `options.SetParameterPolicy<RegexInlineRouteConstraint>("regex")`. The framework compiles route regexes with `IgnoreCase`, `Compiled` and `CultureInvariant` and a **10-second match timeout**, so a pathological pattern cannot hang a request forever, but a cheap ordinal check like the class above is still faster. ## Testing a constraint Because `Match` is a plain method, a unit test needs no server: create the constraint, build a `RouteValueDictionary` such as `new() { ["isbn"] = "9780261103573" }`, and call `Match(null, null, "isbn", values, RouteDirection.IncomingRequest)`. Cover a valid ISBN, a wrong check digit, 12 and 14 digits, and non-digit characters. An integration test through the test host then proves the name is registered and the template resolves it. ## Should it be a constraint at all? A checksum failure in either approach never reaches the endpoint: it drops out of matching, so the request falls through to another route such as `/books/{slug}` or, if none matches, ends as a **404**. The routing docs say custom constraints are rarely needed and suggest model binding first. A reasonable split for a bookshop: - Use a constraint when it **separates routes**: `/books/{isbn:isbn13}` beside `/books/{slug}`, so `9780261103573` and `the-hobbit` reach different endpoints. - Validate inside the endpoint when the URL is clearly an ISBN and the client deserves a **400** saying the check digit is wrong. ## What interviewers listen for - The `Match` signature and the two `RouteDirection` values. - Registration through `RouteOptions`, ideally `SetParameterPolicy`. - Regex escaping, anchoring and the slim builder gap. - Awareness that any constraint failure is a 404, not a validation error.
- Why does IRouteConstraint.Match receive a RouteDirection, and what should an ISBN constraint do with it?The same constraint runs when routing matches a request (`IncomingRequest`) and when `LinkGenerator` or `Url.Action` builds a URL (`UrlGeneration`). Most constraints, including an ISBN check, should apply the same rule both ways so the app never generates a link it would refuse. A constraint that depends on request data must also cope with a null `HttpContext` during generation outside a request.
- Why prefer RouteOptions.SetParameterPolicy over ConstraintMap.Add?`SetParameterPolicy<T>` carries a `DynamicallyAccessedMembers` annotation, so the trimmer keeps the constraint's constructors. The `ConstraintMap` getter is marked `[RequiresUnreferencedCode]`, so a trimmed or Native AOT app gets a warning and could lose the type. Both register the same name; one is safe under trimming.
- Can a custom route constraint take constructor arguments or services?Yes. Routing activates the constraint itself: arguments written in the template, such as `isbn13(978)`, are converted with the invariant culture into `IConvertible` constructor parameters, and parameters of any other type are resolved from the service provider. Keep injected dependencies cheap and thread-safe, because one instance serves every request on that endpoint.
- Expects a failed custom constraint to produce a 400 the client can act on.
- Writes regex(^97(8|9)\d{10}$) in a template without doubling the braces.
- Omits ^ and $ and assumes a regex constraint matches the whole value.
- Registers the constraint with AddScoped instead of in RouteOptions.
- Assumes the regex constraint works in a CreateSlimBuilder app with no extra setup.
- Dereferences httpContext in Match without handling link generation outside a request.
Assumes ASP.NET Core 10; since .NET 8, CreateSlimBuilder (the webapiaot template) registers routing without the regex constraint, and RouteOptions.SetParameterPolicy is the trimming-safe registration.