Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 52 ยท Routing and Minimal APIs

Route Templates and Constraints

Master ASP.NET Core route templates: parameters, optional and catch-all segments, defaults, constraints such as int, guid and regex, named routes and link generation.

Routing connects a URL to the code that should answer it. The connection is described by a route template: a pattern such as /products/{id} where the part in braces is a variable. When a request arrives, the router compares its path with every template, picks the best match and hands the extracted values to your handler.

Templates can do more than capture text. They can make segments optional, swallow a whole tail of the path, supply defaults and demand that a value looks a certain way (an integer, a GUID, two letters). In this lesson you will use all of that, and finish by doing the reverse: generating URLs from route names instead of hard-coding strings.

Literals and parameters

A template is a list of segments separated by /. A segment is either a literal that must match exactly (compared case-insensitively) or a parameter in braces.

C#
app.MapGet("/about", ...);                    // only /about (also /About, /ABOUT)
app.MapGet("/products/{id}", ...);            // /products/7, /products/abc
app.MapGet("/blog/{year}/{month}", ...);      // /blog/2026/10

The name in braces binds to a handler parameter of the same name. The router also converts the text to the parameter's type, so (int id) receives an integer. If the text cannot be converted (for example /products/abc to an int), binding fails and the framework answers 400 Bad Request. Later in this lesson you will see how a constraint turns that case into a clean 404 instead.

C# Parameters in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Notice that /ABOUT matches (literals ignore case), /products/abc fails with 400 because abc is not an integer, and /blog/2026 gives 404 because no template has only one segment after /blog.

Optional parameters and defaults

Add ? to make a parameter optional, or =value to give it a default. The handler parameter must be nullable (for ?) or can be a plain type (for defaults).

C#
app.MapGet("/search/{term?}", (string? term) => ...);     // /search and /search/cats
app.MapGet("/list/{page=1}", (int page) => ...);          // /list means page 1

Only the last parameters of a template can be optional, since the router has to know which segment is missing.

Catch-all parameters

A parameter starting with * swallows the rest of the path, including slashes. Two stars, {**path}, keep the slashes as they are, which is nearly always what you want. This is how file servers and proxies map /files/a/b/c.txt to one handler.

C# Optional, default and catch-all

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

/files alone matches the template (a catch-all may be empty), but the handler's non-nullable string path has nothing to bind, so the framework answers 400. Declare the parameter as string? path if the bare path should work too.

A catch-all hands you attacker-controlled text. If you use it as a file path, never combine it with a base folder without checking that the final path stays inside that folder (watch for .. segments).

Constraints

A constraint restricts what a parameter may contain. Write it after a colon: {id:int}. If the value does not satisfy the constraint, the template does not match, so the request falls through to other routes or ends in a clean 404. That is different from a type conversion failure, which gives 400.

Constraint Matches Example
int, long integers {id:int}
double, decimal, float numbers {price:decimal}
bool true or false {active:bool}
guid a GUID {token:guid}
datetime a date and time {day:datetime}
alpha letters a-z only {code:alpha}
length(n) or length(min,max) text length {code:length(2)}
minlength(n), maxlength(n) text length bounds {name:minlength(3)}
min(n), max(n), range(a,b) numeric range {page:min(1)}
regex(...) a regular expression {sku:regex(^[A-Z]{{3}}-\d{{4}}$)}

Combine constraints by chaining colons: {id:int:min(1)}. Regular expressions in route constraints ignore case (so abc-1234 also matches [A-Z]{{3}}). In a regular expression inside a template, braces must be doubled ({{3}}) and, in a C# string literal, backslashes doubled (as in "\\d"), because the template parser uses braces itself.

Constraints also let two routes share a shape. Here /items/42 and /items/new look alike, but the integer constraint tells them apart:

C# Constraints decide which route matches

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Look at /items/new: it did not match {id:int:min(1)}, because new is not an integer, so the router moved on to the literal route. Without the constraint, would have grabbed it. Also note the literal route is preferred when both match, because a literal segment is more specific than a parameter.

Constraints are for routing, not for validation. Use them to choose between routes and to reject obviously impossible shapes early. For business rules ("this id must exist", "the price must be positive"), validate in the handler and return a helpful 400 or 404; see Model Validation.

Which route wins?

When several templates match one path, ASP.NET Core picks the most specific one, and it does this regardless of the order in which you wrote them. In rough order of precedence: literal segments beat parameters with constraints, which beat plain parameters, which beat catch-alls. If two templates are equally specific, the request fails with an AmbiguousMatchException (a 500 error), which is a bug in your route table that you want to find early.

flowchart TD
    R["Request path: /items/new"] --> A["/items/new<br/>literal"]
    R --> B["/items/{id:int}<br/>constraint fails"]
    R --> C["/items/{name}<br/>plain parameter"]
    A --> W["Winner: the literal route"]
    B -.rejected.-> W
    C -.matches but less specific.-> W

A literal route beats a plain parameter, and a failed constraint removes a candidate altogether.

Hard-coded URLs break when you rename a route. ASP.NET Core can build URLs from the route itself. Give the endpoint a name with WithName(...), and ask LinkGenerator for a path by name and values:

C# Generating links from route names

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Results.Created with the generated path means that if you later change the template to /library/books/{id}, the Location header follows automatically. Values that are not part of the template (like format) become query-string entries. Names must be unique across the app, so a good habit is a verb plus noun: GetBook, ListBooks.

Common mistakes

  • 400 instead of 404. with an int parameter answers 400 for text. Add :int when "not a number" should simply mean "no such page".
  • Optional in the middle. {a?}/{b} is not allowed; optional parameters go last.
  • Ambiguous routes. /items/{name} and /items/{code} are equally specific. Add constraints or merge them.
  • Regex braces and backslashes. Double the braces and escape backslashes inside regex(...).
  • Trailing slash assumptions. /about and /about/ both match the same endpoint, so do not rely on the difference.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What happens for GET /products/abc when the route is /products/{id} and the handler takes int id?

    The route matches, but binding the text to an int fails, so the framework answers 400 Bad Request. With {id:int} the route would not match and the answer would be 404.
  2. 2. Which template makes /files/a/b/c.txt bind path to a/b/c.txt?

    A catch-all parameter such as {**path} captures the rest of the path, slashes included.
  3. 3. Two routes exist: /items/new and /items/{id:int}. Which handles GET /items/new?

    new fails the int constraint, and a literal segment is the most specific match anyway. Registration order does not decide.
  4. 4. Why use WithName and LinkGenerator?

    Generated links stay correct when templates change, and extra route values become query-string parameters.
  5. 5. Where may an optional parameter such as {id?} appear?

    Optional parameters must come last, so the router knows which segment is missing.

Summary

  • A route template mixes literal segments and ; literals ignore case.
  • {x?} makes a parameter optional, {x=5} gives a default, {**x} captures the rest of the path.
  • Type conversion failures give 400; failed constraints (:int, :guid, :min(1), :alpha, :regex(...)) make the route not match and usually give 404.
  • The most specific route wins, independent of registration order; equally specific routes are ambiguous and fail.
  • Name endpoints with WithName and build URLs with LinkGenerator instead of typing them twice.
  • Treat catch-all values as untrusted input.

Next: Route Groups and Organizing Endpoints