Routing
Routing decides which endpoint handles a URL. In ASP.NET Core it is endpoint routing: the route is matched first, the handler runs at the end, and route templates plus constraints decide which endpoint wins.
42.1 Why is it used?
- Maps a URL + HTTP method to exactly one handler (minimal API endpoint or controller action).
- Route templates pull values out of the URL (/products/{id}) and pass them to the handler.
- Constraints separate routes that have the same shape (/products/42 vs /products/mixer-grinder).
- Named routes let you generate links instead of hardcoding URLs.
42.2 The bug: one URL, two routes
C#
var builder = WebApplication.CreateBuilder(args);var app = builder.Build(); app.MapGet("/products/{id}", (int id) => $"Product by id: {id}"); app.MapGet("/products/{slug}", (string slug) => $"Product by slug: {slug}"); app.Run();Output
$ dotnet buildwarning ASP0022: Route '/products/{id}' conflicts with another handler route. $ curl -i localhost:5042/products/42HTTP/1.1 500 Internal Server ErrorContent-Type: text/plain; charset=utf-8AmbiguousMatchException: The request matched multiple endpoints. Matches:HTTP: GET /products/{id}HTTP: GET /products/{slug}- {id} and {slug} are just placeholder names, so for routing both templates have the same shape.
- 42 matches both because the int type of the handler parameter is not checked during routing.
- Two equal matches = AmbiguousMatchException = 500. The build warning ASP0022 warned about it.
- Step 1
1.GET /products/42 arrives
- Step 2
2.{id} and {slug} are just names: same shape
- Step 3
3.42 matches both templates (int not checked)
- Step 4
4.AmbiguousMatchException -> 500
Tell routing: id is only a number
42.3 Fix: route constraint
C#
app.MapGet("/products/{id:int}", (int id) => $"Product by id: {id}"); app.MapGet("/products/{slug}", (string slug) => $"Product by slug: {slug}");Output
$ curl -i localhost:5042/products/42HTTP/1.1 200 OKContent-Type: text/plain; charset=utf-8Product by id: 42 $ curl -i localhost:5042/products/mixer-grinderHTTP/1.1 200 OKContent-Type: text/plain; charset=utf-8Product by slug: mixer-grinder- {id:int} is a route constraint: the id route matches only integers.
- mixer-grinder is not an integer, so it goes to the slug route.
- A route with a constraint is more specific, so it gets priority when a number comes in.
42.4 How endpoint routing works
C#
var app = WebApplication.Create(args); app.Use(async (context, next) =>{ var endpoint = context.GetEndpoint(); Console.WriteLine( $"Matched: {endpoint?.DisplayName}"); await next();}); app.MapGet("/products/{id:int}", (int id) => $"Product by id: {id}");app.MapGet("/products/{slug}", (string slug) => $"Product by slug: {slug}");app.Run();Output
$ dotnet run --urls http://localhost:5042info: Microsoft.Hosting.Lifetime[14] Now listening on: http://localhost:5042Matched: HTTP: GET /products/{id:int}Matched: HTTP: GET /products/{slug}- Every MapGet registers an endpoint.
- UseRouting (added automatically at the start) matches the URL and selects an endpoint but does not run it yet.
- Middleware in between can read the selected endpoint with context.GetEndpoint(); this is how authentication, authorization and CORS know which endpoint will run.
- Step 1
1.Request comes in
- Step 2
2.UseRouting: path + HTTP method + constraints -> select endpoint
- Step 3
3.Middleware in between (auth, CORS) can see the endpoint
- Step 4
4.Selected endpoint's handler runs at the end
- Step 5
5.No match -> 404, two equal matches -> 500
Match first, run at the end
42.5 Route templates: optional, default, catch-all
C#
app.MapGet("/orders/{page:int?}", (int? page) => $"Orders page {page ?? 1}"); app.MapGet("/shop/{category=all}", (string category) => $"Category: {category}"); app.MapGet("/docs/{**path}", (string path) => $"Doc: {path}");Output
$ curl localhost:5042/ordersOrders page 1$ curl localhost:5042/orders/3Orders page 3$ curl localhost:5042/shopCategory: all$ curl localhost:5042/shop/kitchenCategory: kitchen$ curl localhost:5042/docs/setup/windows/installDoc: setup/windows/install| Template | Meaning | Example |
|---|---|---|
| {page:int?} | Optional parameter; handler takes int? | /orders and /orders/3 |
| {category=all} | Default value when missing | /shop -> all |
| {**path} | Catch-all: rest of the path with slashes | /docs/setup/windows/install |
| {id:int} | Type constraint | /products/42 only |
42.6 More constraints: min, regex, alpha, length
C#
app.MapGet("/products/{id:int:min(1)}", (int id) => $"Product by id: {id}") app.MapGet("/pincode/{pin:regex(^\\d{{6}}$)}", (string pin) => $"Delivery to {pin}"); app.MapGet("/coupons/{code:alpha:length(6)}", (string code) => $"Coupon {code}");Output
$ curl -i localhost:5042/pincode/110001HTTP/1.1 200 OKContent-Type: text/plain; charset=utf-8Delivery to 110001 $ curl localhost:5042/coupons/DIWALICoupon DIWALI$ curl -i localhost:5042/coupons/SALE50HTTP/1.1 404 Not Found $ curl -i localhost:5042/pincode/1100HTTP/1.1 404 Not FoundContent-Length: 0- {id:int:min(1)}: integer and at least 1. Constraints can be chained with colons.
- regex(^\d{{6}}$): only a 6 digit pincode (braces inside a template are escaped by doubling).
- alpha:length(6): only 6 letters, so DIWALI matches but SALE50 gives 404.
- Other common ones: guid, bool, long, minlength, maxlength, range(a,b).
42.7 Checkpoint: /products/0?
C#
app.MapGet("/products/{id:int:min(1)}", (int id) => $"Product by id: {id}") app.MapGet("/products/{slug}", (string slug) => $"Product by slug: {slug}");Output
$ curl -i localhost:5042/products/0HTTP/1.1 200 OKContent-Type: text/plain; charset=utf-8Product by slug: 0- Many expect 404, but min(1) fails so the id route simply drops out.
- The slug route accepts any text, so 0 goes there: "Product by slug: 0".
- A constraint only chooses a route; it does not validate input.
42.8 Attribute routes on controllers
C#
using Microsoft.AspNetCore.Mvc; [ApiController][Route("api/[controller]")]public class OrdersController : ControllerBase{ [HttpGet("{id:int}", Name = "GetOrder")] public string Get(int id) => $"Order {id}"; [HttpGet("latest")] public string Latest() => "Latest order";}Output
$ curl -i localhost:5042/api/orders/5HTTP/1.1 200 OKContent-Type: text/plain; charset=utf-8Order 5 $ curl -i localhost:5042/api/orders/latestHTTP/1.1 200 OKContent-Type: text/plain; charset=utf-8Latest order- [Route("api/[controller]")] is the prefix; the [controller] token becomes Orders from the class name.
- [HttpGet("{id:int}")] joins the prefix: /api/orders/5.
- [HttpGet("latest")] also sits under the prefix: /api/orders/latest.
- Name = "GetOrder" names the route for link generation.
42.9 Link generation: LinkGenerator
C#
app.MapGet("/products/{id:int:min(1)}", (int id) => $"Product by id: {id}") .WithName("ProductById"); app.MapGet("/links", (HttpContext http, LinkGenerator links) => new{ path = links.GetPathByName( "ProductById", new { id = 7 }), url = links.GetUriByName(http, "ProductById", new { id = 7 }), order = links.GetPathByName( "GetOrder", new { id = 5 })});Output
$ curl -i localhost:5042/linksHTTP/1.1 200 OKContent-Type: application/json; charset=utf-8{ "path": "/products/7", "url": "http://localhost:5042/products/7", "order": "/api/Orders/5"}- Hardcoded URLs break when a route changes; generate them from names instead.
- WithName("ProductById") names a minimal API endpoint; controller routes use Name = "...".
- GetPathByName builds the path, GetUriByName builds the full URL (needs HttpContext for scheme and host).
42.10 Common mistakes
- Ignoring warning ASP0022: at runtime it becomes a 500.
- Leading slash in an action template: a template that starts with / ignores the controller prefix, so /api/orders/latest gives 404 and the endpoint lives at /latest.
- Treating constraints as validation: when a constraint fails the user gets a 404 or another route, not a clear error. Validate rules like price in the handler.
- Hardcoding URLs in responses instead of using named endpoints.
C#
[Route("api/[controller]")]public class OrdersController : ControllerBase{ [HttpGet("/latest")] public string Latest() => "Latest order";} // GET /api/orders/latest -> 404// GET /latest -> 200Right: [HttpGet("latest")] without a slash combines with the prefix into /api/orders/latest (200).
42.11 Routing rules
- Never ignore ASP0022.
- Routes with the same shape: add a type constraint (int, guid).
- Optional {x?}: use a nullable type in the handler.
- Prefix on the controller, action template without a leading /.
- URLs: WithName + LinkGenerator, never hardcoded.
42.12 Interview tips
- Endpoint routing works in two steps: UseRouting matches an endpoint (path, method, constraints) and the same endpoint runs at the end of the pipeline.
- Middleware between them can read the endpoint (GetEndpoint), which is how auth and CORS apply per endpoint.
- Constraints resolve ambiguity between routes; they are not input validation (failure = 404 or another route).
- For links use named endpoints and LinkGenerator.