How does model binding work differently between controllers (using [FromBody], [FromQuery] attributes) and minimal APIs (using parameter inference)?
Short answer
Controllers require explicit binding source attributes ([FromBody], [FromQuery], [FromRoute]) in ambiguous cases, though [ApiController] provides some automatic inference.
Advertisement
AModel answer
Controllers require explicit binding source attributes ([FromBody], [FromQuery], [FromRoute]) in ambiguous cases, though [ApiController] provides some automatic inference. Minimal APIs infer binding sources more aggressively by default based on parameter type and route pattern matching (a parameter matching a route template segment binds from the route, a complex type typically binds from the body), reducing the need for explicit attributes in common cases while still supporting them for disambiguation when needed.
// Minimal API: automatic inference based on parameter characteristics
app.MapPost("/products/{id}", (int id, ProductDto dto, [FromServices] IProductService service) => {
// id inferred from route, dto inferred from body, service explicitly from DI
return service.Update(id, dto);
});Real-world example
A minimal API endpoint binds its route parameter, request body, and injected service all through inference and one explicit [FromServices] attribute, achieving the same result as a controller action with more verbose explicit attributes on every parameter.
Likely follow-ups
- When does minimal API's automatic inference get it wrong, requiring explicit attributes?
- How does model binding performance compare between the two approaches?
Related topics