Routing and binding
Routing and binding
Routing selects an endpoint using the request path and method. Parameter binding then turns request data into the handler’s typed arguments. A constraint narrows route selection; binding and validation solve different problems.
Route values are parts of the path, query values follow the question mark, and a request body may contain JSON. A parameter name matching a route token can bind from the path; simple other parameters often bind from the query. A complex DTO on POST normally binds from JSON unless other binding rules apply. Explicit attributes make boundaries visible. A nullable or defaulted query parameter can be absent, but malformed supplied input may still cause 400. A route constraint is for route selection, not domain validation. Pagination needs stable ordering and a maximum page size. CancellationToken binds to request abort in Minimal APIs; pass it to downstream asynchronous operations.
Baseline: .NET 10 / C# 14. Each code block is an independent static example with a companion Web SDK project. Read the endpoint registration and client checks first; the surrounding host harness is repeated for standalone use. Expected observations are reasoned, not executed. Run only in a clean, isolated local environment with an approved SDK; no launch profile, external network or real data. The OpenAPI package example additionally requires approved restore.
Bind route and query values
Use explicit binding attributes; a query default is used only when omitted.
using System.Net;using System.Net.Http.Json;using System.Text;using System.Text.Json;using Microsoft.AspNetCore.Http.HttpResults;using Microsoft.AspNetCore.Mvc;
// Standalone lab: run in a clean, isolated environment only.var builder = WebApplication.CreateBuilder(new WebApplicationOptions{ Args = Array.Empty<string>(), EnvironmentName = "Production", ContentRootPath = AppContext.BaseDirectory});builder.Configuration.Sources.Clear();builder.Logging.ClearProviders();builder.WebHost.ConfigureKestrel(options =>{ options.Listen(IPAddress.Loopback, 0); options.Limits.MaxRequestBodySize = 16 * 1024;});await using var app = builder.Build();app.MapGet("/books/{id:int}", ([FromRoute] int id, [FromQuery] int page = 1) => $"{id}:{page}");using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(15));await app.StartAsync(deadline.Token);try{ var address = new Uri(app.Urls.Single()); if (address.Host != "127.0.0.1" || address.Scheme != "http") throw new InvalidOperationException("Unexpected listener address."); using var client = new HttpClient(new HttpClientHandler { UseProxy = false, AllowAutoRedirect = false }) { BaseAddress = address }; foreach (string path in new[] { "/books/2?page=3", "/books/2" }) Console.WriteLine(await client.GetStringAsync(path, deadline.Token));}finally{ using var shutdown = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await app.StopAsync(shutdown.Token);}The ID comes from the path and page from the query; the declared default supplies 1.
Expected observation (reasoned, not executed):
2:32:1Compare constraint and binding failure
Numeric route constraint rejects a nonnumeric segment before binding.
using System.Net;using System.Net.Http.Json;using System.Text;using System.Text.Json;using Microsoft.AspNetCore.Http.HttpResults;using Microsoft.AspNetCore.Mvc;
// Standalone lab: run in a clean, isolated environment only.var builder = WebApplication.CreateBuilder(new WebApplicationOptions{ Args = Array.Empty<string>(), EnvironmentName = "Production", ContentRootPath = AppContext.BaseDirectory});builder.Configuration.Sources.Clear();builder.Logging.ClearProviders();builder.WebHost.ConfigureKestrel(options =>{ options.Listen(IPAddress.Loopback, 0); options.Limits.MaxRequestBodySize = 16 * 1024;});await using var app = builder.Build();app.MapGet("/strict/{id:int}", (int id) => id);app.MapGet("/plain/{id}", (int id) => id);using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(15));await app.StartAsync(deadline.Token);try{ var address = new Uri(app.Urls.Single()); if (address.Host != "127.0.0.1" || address.Scheme != "http") throw new InvalidOperationException("Unexpected listener address."); using var client = new HttpClient(new HttpClientHandler { UseProxy = false, AllowAutoRedirect = false }) { BaseAddress = address }; foreach (string path in new[] { "/strict/abc", "/plain/abc", "/strict/2" }) { using var response = await client.GetAsync(path, deadline.Token); Console.WriteLine((int)response.StatusCode); }}finally{ using var shutdown = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await app.StopAsync(shutdown.Token);}The first path has no matching endpoint; the second matches but integer parsing fails; the final succeeds.
Expected observation (reasoned, not executed):
404400200Bind JSON and distinguish malformed input
Use a small public DTO; this calculation does not write state.
using System.Net;using System.Net.Http.Json;using System.Text;using System.Text.Json;using Microsoft.AspNetCore.Http.HttpResults;using Microsoft.AspNetCore.Mvc;
// Standalone lab: run in a clean, isolated environment only.var builder = WebApplication.CreateBuilder(new WebApplicationOptions{ Args = Array.Empty<string>(), EnvironmentName = "Production", ContentRootPath = AppContext.BaseDirectory});builder.Configuration.Sources.Clear();builder.Logging.ClearProviders();builder.WebHost.ConfigureKestrel(options =>{ options.Listen(IPAddress.Loopback, 0); options.Limits.MaxRequestBodySize = 16 * 1024;});await using var app = builder.Build();app.MapPost("/estimate", ([FromBody] Estimate input) => input.Quantity is >= 1 and <= 100 ? Results.Ok(input.Quantity * 3) : Results.BadRequest());using var deadline = new CancellationTokenSource(TimeSpan.FromSeconds(15));await app.StartAsync(deadline.Token);try{ var address = new Uri(app.Urls.Single()); if (address.Host != "127.0.0.1" || address.Scheme != "http") throw new InvalidOperationException("Unexpected listener address."); using var client = new HttpClient(new HttpClientHandler { UseProxy = false, AllowAutoRedirect = false }) { BaseAddress = address }; using var valid = await client.PostAsJsonAsync("/estimate", new { quantity = 4 }, deadline.Token); using var invalid = await client.PostAsync("/estimate", new StringContent("{", Encoding.UTF8, "application/json"), deadline.Token); Console.WriteLine($"{(int)valid.StatusCode}:{await valid.Content.ReadAsStringAsync(deadline.Token)}"); Console.WriteLine((int)invalid.StatusCode);}finally{ using var shutdown = new CancellationTokenSource(TimeSpan.FromSeconds(5)); await app.StopAsync(shutdown.Token);}record Estimate(int Quantity);Valid JSON reaches the handler; malformed JSON fails binding. Domain bounds prevent out-of-range estimates.
Expected observation (reasoned, not executed):
200:12400Common mistakes and design boundaries
Do not rely on constraints to send clear validation errors. Binding is not authorization. Do not accept unbounded page sizes, concatenate unvalidated SQL sort expressions, or assume nullable types convert malformed data to null. JSON with a correct shape can still violate business rules.
Apply your understanding
Design GET /books/{id} with a required numeric ID and optional page defaulting to 1. Predict the status for a nonnumeric ID with and without an int constraint and for page=oops.
Complete the linked manual practice and knowledge check. The examples are not automated ByteMind assessments.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Routing and binding — knowledge check
Apply the lesson concepts to the following scenarios.
Where does id come from in /books/{id:int}?
What usually happens when /strict/abc fails the only int constraint?
A matched unconstrained route has int id, but id is abc. What occurs?
What does an omitted optional page=1 parameter use?
Which step checks quantity <= 100?