
Where Did That Parameter Come From? Parameter Binding in Minimal APIs
- كاتب موثّق
- .NET 10
محتويات المقال
{id} to {orderId} because it reads better in the OpenAPI document. The handler still says int id. The build is clean, no analyzer complains, and in production GET /orders/42 starts answering 400 with an empty body. At the default log level, nothing is logged. The parameter didn't vanish: it quietly moved from the route to the query string, where nobody sends it.
The common misconception
[FromQuery], [FromBody] and [AsParameters] are there for readability or documentation, and leaving them out changes nothing.
(int id) with a route of /orders/{id} reads the route. (Order order) on a POST reads the JSON body. A registered service arrives from without any attribute. The official samples rarely use attributes, so it's easy to conclude the framework is smart enough to always work it out.
What actually happens
The rules, in order
An explicit attribute: [FromRoute],[FromQuery],[FromHeader],[FromBody],[FromForm],[FromServices]or[AsParameters].A special type: HttpContext,HttpRequest,HttpResponse,ClaimsPrincipal,CancellationToken, a form or file type,StreamorPipeReader.A type with a static BindAsyncmethod.A string, or a type with a staticTryParsemethod such asintorGuid: from the route if its name appears in the route template, otherwise from the query string.A type registered as a service: from dependency injection. Anything else: from the request body.
The name is the contract
{id} to {orderId} and int id no longer matches, so it's read from ?id= instead. Parameters are required unless they're nullable or have a default value, so a request without ?id= fails with "Required parameter "int id" was not provided from query string." In Development, that's a BadHttpRequestException on the developer exception page. In other environments, ThrowOnBadRequest is off: the client gets a 400 with an empty body and the reason is logged only at Debug level.
Headers are never inferred
string apiKey meant for the X-Api-Key header is bound from ?apiKey=. Clients that send the header get a 400, and the "fix" someone eventually finds is to put the key in the URL, where it ends up in access logs and browser history.
Complex types fall through to the body
OrderQuery(string? Status, int Page) has no TryParse and isn't a service, so it lands on rule 6: the body. But GET, HEAD, OPTIONS and DELETE don't bind from the body implicitly, so the endpoint can't be built: "Body was inferred but the method does not allow inferred body parameters." A service you forgot to register falls through the same way, because it's just a type the container doesn't know.
[AsParameters] is the opt-in.
The orders endpoints, fixed
var builder = WebApplication.CreateBuilder(args);var app = builder.Build();// {orderId} in the route, id in the handler: id is read from ?id=app.MapGet("/orders/{orderId:int}", (int id) => $"Order {id}");// headers are never inferred: apiKey is read from ?apiKey=app.MapGet("/reports", (string apiKey) => "report");// a record isn't read from the query string: it's inferred as the bodyapp.MapGet("/orders", (OrderQuery query) => query);app.Run();public record OrderQuery(string? Status, int Page = 1);using Microsoft.AspNetCore.Mvc;var builder = WebApplication.CreateBuilder(args);var app = builder.Build();app.MapGet("/orders/{orderId:int}", (int orderId) => $"Order {orderId}");app.MapGet("/reports", ([FromHeader(Name = "X-Api-Key")] string apiKey) => "report");// each property binds by the usual rules: Status and Page from the queryapp.MapGet("/orders", ([AsParameters] OrderQuery query) => query);app.Run();public record OrderQuery(string? Status, int Page = 1);/orders handler can't be. Comment that endpoint out and, outside Development, /orders/5 answers an empty 400, and so does /reports with the header set. The second version answers Order 5, returns {"status":"open","page":2} for /orders?status=open&page=2, falls back to page 1 when page is missing, and still rejects ?page=two with a 400.
What you wrote vs. what binds
int id with route {orderId} | ?id= | |
string apiKey meant as a header | ?apiKey= | |
OrderQuery query on a GET | ||
[AsParameters] OrderQuery query |
How to apply it in your project
Match route names on purpose For every {name}in a route template, check that a handler parameter has that exact name, or uses[FromRoute(Name = ...)]. Do it again whenever someone renames a route.Mark headers, forms and bodies on GET Use [FromHeader]for anything from a header,[FromForm]for form posts, and[FromBody]if a GET or DELETE really must read a body. None of these is ever inferred.Use AsParameters for filter objects When a GET takes several query values, group them in a record and mark the parameter [AsParameters]. It binds each property by the normal rules; it isn't recursive model binding, so keep the record flat.Make one request in your tests An integration test that sends any request through the app builds every endpoint, so a parameter the rules can't place fails the test instead of the first production call.
Key takeaways
Minimal APIs bind parameters with an ordered list of rules: attribute, special type, BindAsync, route-or-query for simple types, services, then the body.A simple parameter is read from the route only if its name matches the template; otherwise it's read from the query string. Headers and forms are never inferred, and complex types fall through to the body, which GET and DELETE don't allow implicitly. A binding mistake shows up at runtime, as an empty 400 or a 500 on every endpoint, so attributes like [FromHeader]and[AsParameters]are behavior, not decoration.
التعليقات (0)