Routing
Routing decides which endpoint handles an incoming request. Every MapGet, MapPost, controller action or Razor Page registers an endpoint with a route template; when a request arrives, the routing middleware compares its method and path against all templates and picks the best match.
Route templates
A template is a path made of segments. Each segment is either literal text or a parameter in braces:
app.MapGet("/", () => "Home"); // exactly /
app.MapGet("/products", () => "All products"); // literal
app.MapGet("/products/{id}", (string id) => quot;Product {id}"); // parameter
app.MapGet("/shops/{shop}/products/{id}", (string shop, string id) => quot;{shop}: {id}");Matching is case-insensitive (/Products matches /products), and a trailing slash is ignored.
| Template | Matches | Doesn't match |
|---|---|---|
/products |
/products, /PRODUCTS/ |
/products/1 |
/products/{id} |
/products/1, /products/abc |
/products, /products/1/reviews |
/files/{*path} |
/files/a, /files/docs/2026/report.pdf |
/file |
/blog/{page?} |
/blog, /blog/3 |
/blog/3/4 |
/blog/{page=1} |
/blog (page = "1"), /blog/7 |
— |
{name?}makes a parameter optional (the handler parameter must then be nullable, e.g.int? page).{name=value}gives a default value.{*name}is a catch-all: it swallows the rest of the path, slashes included.
Route constraints
A constraint, written after a colon, restricts what a parameter accepts. If the constraint fails, the route simply doesn't match — the request falls through to other routes, and if none match the client gets 404.
| Constraint | Example | Accepts |
|---|---|---|
int, long |
{id:int} |
42, -1 |
guid |
{id:guid} |
0f8fad5b-d9cb-469f-a165-70867728950e |
bool |
{active:bool} |
true, False |
alpha |
{code:alpha} |
Letters only |
minlength(n), maxlength(n), length(a,b) |
{slug:minlength(3)} |
String length rules |
min(n), max(n), range(a,b) |
{page:range(1,100)} |
Numeric ranges |
regex(…) |
{sku:regex(^[A-Z]{{3}}-\\d+$)} |
Pattern (escape { } by doubling) |
Constraints can be combined: {id:int:min(1)}.
app.MapGet("/orders/{id:int:min(1)}", (int id) => quot;Order #{id}");
app.MapGet("/orders/{code:alpha:length(3)}", (string code) => quot;Order with code {code}");$ curl -s localhost:5000/orders/15
$ curl -s localhost:5000/orders/xyz
$ curl -s -o /dev/null -w "%{http_code}\n" localhost:5000/orders/0
$ curl -s -o /dev/null -w "%{http_code}\n" localhost:5000/orders/abcdOrder #15
Order with code xyz
404
404
Tip: Use constraints to disambiguate routes, not to validate input. A request for
/orders/0returning 404 is confusing; for "id must be positive" it is often clearer to accept anyintand return400 Bad Requestwith an explanation.
Which route wins?
When several templates could match, ASP.NET Core does not use registration order. It ranks them by specificity:
- Literal segments beat parameters (
/products/featuredbeats/products/{id}). - Parameters with constraints beat parameters without.
- Normal parameters beat optional parameters and catch-alls.
If two endpoints are equally good, the request fails with an AmbiguousMatchException (500) — a sign you need a constraint or a different template.
This little matcher shows the scoring idea in plain C#:
using System;
using System.Collections.Generic;
using System.Linq;
var routes = new[] { "/products/{id}", "/products/featured", "/products/{id:int}", "/{*path}" };
foreach (var path in new[] { "/products/featured", "/products/7", "/products/abc", "/about/team" })
{
var best = routes
.Select(r => (Route: r, Score: Score(r, path)))
.Where(x => x.Score >= 0)
.OrderByDescending(x => x.Score)
.First();
Console.WriteLine(quot;{path,-20} -> {best.Route}");
}
// Higher score = more specific. -1 = no match.
static int Score(string template, string path)
{
string[] t = template.Trim('/').Split('/');
string[] p = path.Trim('/').Split('/');
int score = 0;
for (int i = 0; i < t.Length; i++)
{
string seg = t[i];
if (seg.StartsWith("{*")) return score + 1; // catch-all: weakest
if (i >= p.Length) return -1;
if (!seg.StartsWith("{"))
{
if (!seg.Equals(p[i], StringComparison.OrdinalIgnoreCase)) return -1;
score += 100; // literal
}
else if (seg.EndsWith(":int}"))
{
if (!int.TryParse(p[i], out _)) return -1;
score += 50; // constrained parameter
}
else score += 10; // plain parameter
}
return t.Length == p.Length ? score : -1;
}/products/featured -> /products/featured
/products/7 -> /products/{id:int}
/products/abc -> /products/{id}
/about/team -> /{*path}
404 and 405
If no template matches the path, routing produces 404 Not Found. If the path matches but not the HTTP method, minimal APIs answer 405 Method Not Allowed:
app.MapGet("/reports", () => "Monthly report");$ curl -s -o /dev/null -w "%{http_code}\n" localhost:5000/nothing-here
$ curl -s -i -X DELETE localhost:5000/reports404
HTTP/1.1 405 Method Not Allowed
Content-Length: 0
Date: Thu, 16 Oct 2026 09:00:00 GMT
Server: Kestrel
Allow: GET
Named routes and link generation
Hard-coding URLs in responses is fragile. Give an endpoint a name with WithName, then generate its URL with LinkGenerator or Results.CreatedAtRoute:
app.MapGet("/books/{id:int}", (int id) => new { Id = id, Title = "Dune" })
.WithName("GetBook");
app.MapGet("/books/latest-link", (LinkGenerator links) =>
links.GetPathByName("GetBook", new { id = 12 })); // "/books/12"
app.MapPost("/books", (Book book) =>
Results.CreatedAtRoute("GetBook", new { id = book.Id }, book));If you later change the template to /library/books/{id:int}, every generated link updates automatically.
Where routing runs in the pipeline
WebApplication adds the routing middleware (UseRouting) at the start of the pipeline and runs the matched endpoint at the end, so you rarely call UseRouting() yourself. Middleware placed after routing can inspect HttpContext.GetEndpoint() — this is how CORS and authorization know which endpoint's rules to apply.
Test yourself
A request for /products/featured arrives. Which template is chosen?
/products/{id}because it was registered first/products/featuredbecause literal segments are more specific- Both run
- Neither — the request is ambiguous
What happens when a request for /orders/abc only matches a template /orders/{id:int} by path shape?
idis set to 0- The handler receives
"abc" - The route does not match, so the result is 404
- 400 Bad Request with a validation message
Which template captures the whole remaining path including slashes?
/files/{path}/files/{path?}/files/{*path}/files/{path:alpha}