ASP.NET Core Interview Question #115

What are model binding sources such as FromRoute, FromQuery, FromBody, FromForm, and FromHeader?

Routing, Controllers & Model Binding Mid-Level Intermediate

Quick Interview Answer

Binding source attributes explicitly tell ASP.NET Core where a value should come from.

Detailed Explanation

Binding source attributes explicitly tell ASP.NET Core where a value should come from.

FromRoute reads route values, FromQuery reads the query string, FromBody reads the request body using an input formatter, FromForm reads form data, and FromHeader reads an HTTP header.

Explicit attributes are particularly helpful in APIs because they make endpoint contracts clear. In many MVC scenarios, conventional model binding can infer common sources without attributes.

Code Example

[HttpPost("orders/{id:int}")]
public IActionResult Update(
    [FromRoute] int id,
    [FromQuery] bool notify,
    [FromBody] UpdateOrderRequest request,
    [FromHeader(Name = "X-Correlation-Id")] string? correlationId)
{
    return Ok();
}