Routing
1. What is Routing?
Routing decides which endpoint handles an HTTP request, based on:
- URL path
- HTTP method
URL + Method → Endpoint
2. Routing Pipeline (Very Important)
Routing happens in two steps:
UseRouting
- Matches the request to an endpoint
- Does not execute it
UseEndpoints
- Executes the matched endpoint
app.UseRouting();
app.UseEndpoints((endpoints) => {
endpoints.MapGet("/hello", async (ctx) => {
await ctx.Response.WriteAsync("Hello");
});
});
UseRoutingmust come beforeUseEndpoints.
3. Map* Methods (Create Endpoints)
Common ones:
MapGetMapPostMapPutMapDeleteMapFallback
endpoints.MapGet("/products", ...);
endpoints.MapPost("/products", ...);
Same path, different HTTP methods → different endpoints.
4. Route Parameters
Required
/products/{id}
Optional
/products/{id?}
Default
/profile/{name=guest}
Access values:
context.Request.RouteValues["id"];
5. Route Constraints
Used to validate route parameters early.
/products/{id:int}
/products/{id:int:range(1,1000)}
/reports/{month:regex(^(jan|apr|jul|oct)$)}
More specific constraints win during matching.
6. Endpoint Selection Rules (Remember This Order)
- More specific routes
- Exact HTTP method
- Stronger constraints
- Registration order
- Fallback route
7. GetEndpoint()
Used after UseRouting to inspect the matched endpoint.
var endpoint = context.GetEndpoint();
Common for logging, auth, diagnostics.
8. Static Files & Routing
app.UseStaticFiles();
app.UseRouting();
- Served from
wwwroot - Bypass routing
- Faster than endpoints
9. One-Sentence Interview Answer 🎯
"Routing in ASP.NET Core maps incoming HTTP requests to endpoints using URL patterns and HTTP methods.
UseRoutingmatches the request,UseEndpointsexecutes it, and more specific routes with stricter constraints take priority."