In an ASP.NET Core Minimal API, how does a MapGet or MapPost handler decide where each of its parameters is bound from?
answer
- the route template's parameter names
- simple type: route, otherwise query
- registered service: resolved from DI
- complex type on MapPost: JSON body
- HttpContext and CancellationToken need nothing
basics
~20 sMinimal APIs infer each parameter's source: a simple type binds from the route if its name is a route parameter, else from the query; registered services come from DI; an unregistered complex type on MapPost is the JSON body.
solid answer
~40 sWhen you call `MapGet`, `MapPost`, `MapPut`, `MapPatch`, `MapDelete` or `MapMethods`, ASP.NET Core inspects the handler's parameters once, when it builds the endpoint, and generates code that fills them on every request. A `string` or any type with a static `TryParse` binds from the route when its name (case-insensitively) matches a `{parameter}` in the template, and from the query string otherwise. A type registered in DI is resolved from `RequestServices` without `[FromServices]`. Special types such as `HttpContext`, `HttpRequest`, `ClaimsPrincipal` and `CancellationToken` are handed over directly. Anything left over, typically a DTO on `MapPost`, is deserialized from the JSON body. With nullable reference types on, as in the `webapi` template, a parameter is required unless it is nullable or has a default, and a missing required value gets a 400 without the handler running.
code
csharp · 13 linesbuilder.Services.AddScoped<IRecipeStore, RecipeStore>();
var app = builder.Build();
// GET /recipes/thai?q=curry&page=2
app.MapGet("/recipes/{cuisine}",
async (string cuisine, string? q, int page, IRecipeStore store, CancellationToken ct) =>
TypedResults.Ok(await store.SearchAsync(cuisine, q, page, ct)));
// POST /recipes with a JSON body
app.MapPost("/recipes", async (RecipeDraft draft, IRecipeStore store) =>
TypedResults.Ok(await store.AddAsync(draft)));
record RecipeDraft(string Title, string Cuisine, string[] Ingredients);go deeper
Recall the five sources (route, query, DI, body, special types) and that the route-versus-query choice comes from the parameter name matching the template.
Explain that inference is decided once when the endpoint is built, which types count as simple, and how nullability and defaults make a parameter optional.
Show you can predict a 400 or 415 before a client hits it, and keep handler signatures explicit enough that a renamed parameter cannot silently move from route to query.
Weigh how much contract you let inference decide implicitly against the readability and review cost of explicit sources across a large set of endpoints.
## Mapping a handler to a route and a verb A **Minimal API** endpoint is a delegate registered on `WebApplication` (an `IEndpointRouteBuilder`) with one of the `Map*` extension methods. Each returns a `RouteHandlerBuilder` you can chain conventions on. | Method | HTTP methods it matches | |---|---| | `MapGet` | GET | | `MapPost` | POST | | `MapPut` | PUT | | `MapPatch` | PATCH | | `MapDelete` | DELETE | | `MapMethods(pattern, methods, handler)` | any list you pass, such as GET and HEAD | | `Map` | every method | The handler can be a lambda, a local function or a method group. Its **parameters are the request contract**: there is no MVC-style pipeline of model binder providers and value providers. ASP.NET Core reads the parameter list once, when the endpoint is built, and generates a request delegate that fills each argument and calls the handler. ## How a parameter's source is inferred Without an explicit attribute, the source follows from the parameter's **type** and **name**: 1. **Special types** are supplied straight from the request: `HttpContext`, `HttpRequest`, `HttpResponse`, `ClaimsPrincipal` (the `User`), `CancellationToken` (`RequestAborted`), plus the form and body types `IFormCollection`, `IFormFile`, `IFormFileCollection`, `Stream` and `PipeReader`. 2. A type with a static **`BindAsync`** method binds itself from the `HttpContext`. 3. A **`string`** or a type with a static **`TryParse`** (all numeric types, `Guid`, `DateTime`, enums and your own `IParsable<T>` types) binds from the **route** when the template contains a parameter with the same name, compared case-insensitively, and from the **query string** otherwise. 4. A type the DI container knows (checked through `IServiceProviderIsService`) is **resolved from `RequestServices`**; `[FromServices]` is optional. 5. Anything else is the **JSON request body**, deserialized with System.Text.Json. Only one parameter can be the body, and GET and DELETE never infer one. ## A worked example: paged recipe search ```csharp builder.Services.AddScoped<IRecipeStore, RecipeStore>(); app.MapGet("/recipes/{cuisine}", (string cuisine, // route: {cuisine} IRecipeStore store, // DI CancellationToken ct, // HttpContext.RequestAborted string? q, // query: ?q=... (optional) int page, // query: ?page=... (required) int pageSize = 20) => // query, optional with a default store.SearchAsync(cuisine, q, page, pageSize, ct)); app.MapPost("/recipes", (RecipeDraft draft, IRecipeStore store) => store.AddAsync(draft)); // draft: JSON body ``` For `GET /recipes/thai?q=curry&page=2`, `cuisine` is `thai`, `q` is `curry`, `page` is 2 and `pageSize` falls back to 20. `IRecipeStore` is registered, so it comes from DI; `RecipeDraft` is not, so `MapPost` reads it from the body. ## Required versus optional Inference also decides whether a value **must** be present: - A parameter is **optional** when it is nullable (`int?`, or `string?` under nullable reference types) or declares a default value. - Everything else is **required**. The `webapi` template turns nullable reference types on, so a plain `string q` is required. - A missing required value, or a value that fails `TryParse` (`?page=two`), short-circuits with **400 Bad Request** and the handler never runs. - A missing or unreadable JSON body for a non-nullable body parameter is also a 400; a body sent with a non-JSON content type is a **415**. ## One handler, several verbs `MapMethods` is the escape hatch when one handler should answer more than one verb, such as GET and HEAD for a cacheable recipe page. The verbs you list matter for inference as well as routing: - If any listed verb is GET, DELETE, HEAD, OPTIONS, TRACE or CONNECT, ASP.NET Core assumes the handler never receives a body and will not infer one. - `Map` without a verb list accepts every method, so it still infers a body for an unregistered complex type. - Separate `MapGet` and `MapPost` registrations on the same pattern are the clearer choice when the two verbs need different parameters. ## What inference does not do - It does not bind a complex type from query-string keys. A `RecipeFilter` class on `MapGet` is not "filled from the query"; you need `[AsParameters]`, `BindAsync` or `TryParse` for that. - It does not use MVC's `IModelBinder`, value providers or `ModelState`; Minimal APIs have their own binder. - It does not guess between sources at run time. The decision is made once per endpoint, so the same request always reaches the same parameter the same way. ## What interviewers listen for - Route versus query decided by the **name** in the template, not by position. - DI parameters needing **no attribute** once the service is registered. - The body being **inferred only for complex types** and never on GET. - Nullability and defaults deciding **required versus optional**, with a 400 rather than a default value when something required is missing.
- The template says {cuisine} but the handler parameter is named Cuisine. Does it still bind from the route?Yes. When ASP.NET Core decides between route and query for a simple parameter, it compares the parameter name with the template's route parameters case-insensitively, so `Cuisine` matches `{cuisine}` and is bound from the route value. A name that matches nothing in the template, such as `kitchen`, is looked up in the query string instead, which silently changes where the value must be sent.
- How do you map one handler to both GET and HEAD?Use `app.MapMethods("/recipes/{cuisine}", new[] { HttpMethods.Get, HttpMethods.Head }, handler)`. `MapMethods` takes any list of method names and returns the same `RouteHandlerBuilder` as `MapGet`. Because GET is in the list, ASP.NET Core will not infer a body parameter for that handler, exactly as for `MapGet`.
- Minimal APIs fill a complex parameter from query-string keys, the way MVC model binding does.
- A service parameter in a Minimal API handler always needs [FromServices].
- A simple parameter binds from the route only when it carries [FromRoute].
- A missing non-nullable int query parameter simply arrives as 0.
- A MapGet handler reads an unregistered DTO parameter from the JSON body.