skip to content

In an ASP.NET Core MVC controller, how do [FromRoute], [FromQuery], [FromHeader] and [FromBody] decide where a stock-adjustment action's parameters come from?

level: juniorimportance: must knowfreq 78%

answer

  1. two readers, not one
  2. value providers: form, route, query
  3. input formatter owns the body
  4. FromHeader(Name = "X-Correlation-Id")
  5. wrong Content-Type on a body: 415

basics

~20 s

Each attribute pins a parameter to one source. [FromRoute], [FromQuery] and [FromHeader] read single named values from route data, the query string or a header; [FromBody] hands the whole request body to an input formatter, by default the System.Text.Json one.

solid answer

~40 s

MVC has two binding machineries. **Value providers** supply named string values: the form, route and query providers are registered by default, and `[FromRoute]`, `[FromQuery]` or `[FromForm]` restrict a parameter to one of them. Headers have no default value provider, so a header is read only when you write `[FromHeader]`, usually with `Name = "X-Correlation-Id"` because C# names cannot hold a hyphen. `[FromBody]` instead selects an **input formatter** by the request's `Content-Type` and deserializes the entire body into one object; with no matching formatter, MVC returns 415. For a stock adjustment I would write `[FromRoute] int warehouseId`, `[FromBody] StockAdjustmentBatch batch` and `[FromHeader(Name = "X-Correlation-Id")] string correlationId`. Without attributes in a plain controller, a complex parameter is filled from form, route and query values, never from the JSON body.

code

http · 5 lines
http
POST /api/warehouses/12/stock-adjustments?dryRun=true HTTP/1.1
Content-Type: application/json
X-Correlation-Id: 4f1c2a

{ "lines": [ { "sku": "BOLT-M8", "delta": -40 } ] }

go deeper

for a junior

Know the five source attributes and write a signature that takes a route id, a JSON body and a header, including the Name on [FromHeader].

for a middle

Explain value providers versus input formatters, the default form-route-query search, and why a JSON body to an unattributed parameter yields defaults.

for a senior

Diagnose silent binding failures from logs and ModelState, and explain the 415 path through UnsupportedContentTypeFilter when a client sends the wrong Content-Type.

for a principal

Argue for explicit source attributes as a team convention on public endpoints, weighing readability and OpenAPI accuracy against relying on inference rules.

## Two machineries behind the attributes ASP.NET Core MVC fills action parameters through **model binding**. The `[From*]` attributes in the `Microsoft.AspNetCore.Mvc` namespace look alike, but they route a parameter to one of two very different readers: | Attribute | Reads from | Machinery | Typical parameter | |---|---|---|---| | `[FromRoute]` | route values matched by the route template | route value provider | `int warehouseId` | | `[FromQuery]` | the query string | query string value provider | `bool dryRun` | | `[FromForm]` | `application/x-www-form-urlencoded` or multipart form fields | form value provider | form models | | `[FromHeader]` | one request header | header model binder | `string correlationId` | | `[FromBody]` | the whole request body | an **input formatter** chosen by `Content-Type` | `StockAdjustmentBatch batch` | A **value provider** answers "what string values exist under this name?". MVC registers its value provider factories in `MvcOptions.ValueProviderFactories` in this order: form, route, query string, then jQuery-style form keys and form files. A model binder asks them for a key, converts the string (or strings) to the parameter type, and records any conversion failure in `ModelState`. An **input formatter** (`IInputFormatter`) works differently: it owns the request body stream and deserializes it in one go. MVC registers `SystemTextJsonInputFormatter` by default, so a JSON body is read with System.Text.Json; XML and Newtonsoft.Json formatters exist as opt-ins. ## The stock-adjustment action ```csharp [Route("api/warehouses/{warehouseId:int}/stock-adjustments")] public class StockAdjustmentsController : ControllerBase { [HttpPost] public IActionResult Post( [FromRoute] int warehouseId, [FromBody] StockAdjustmentBatch batch, [FromHeader(Name = "X-Correlation-Id")] string correlationId, [FromQuery] bool dryRun = false) { // warehouseId from the URL, batch from the JSON body, // correlationId from a header, dryRun from ?dryRun=true return Accepted(); } } ``` - `warehouseId` matches the `{warehouseId:int}` route parameter by name; the `:int` constraint also keeps `/warehouses/abc` from matching at all. - `batch` is deserialized by the JSON input formatter from the body. - `correlationId` needs `Name`, because the attribute otherwise looks for a header literally called `correlationId`. - `dryRun` is optional in the query string; its C# default is used when the key is absent. ## What happens when you leave the attributes off In a controller **without** `[ApiController]`, an unattributed parameter has no fixed source. MVC searches the registered value providers (form, then route, then query) and takes the first match. Two consequences catch people out: 1. **Headers are never searched by default.** There is no built-in header value provider, so a header reaches an action only through `[FromHeader]` (or by reading `Request.Headers` yourself). 2. **The body is never read.** An unattributed complex type such as `StockAdjustmentBatch` is built by the complex-object binder from form, route and query keys. A JSON POST therefore produces an instance with default property values and no binding error; only validation attributes on the model may complain afterwards. `[ApiController]` changes this with its own inference rules (complex types from the body, route-template names from the route, the rest from the query). Those rules belong to controller conventions; the explicit attributes behave the same with or without it. ## Edges worth knowing - **Wrong content type.** When a `[FromBody]` parameter meets a `Content-Type` no input formatter accepts, the body binder records an `UnsupportedContentTypeException`, and MVC's globally registered `UnsupportedContentTypeFilter` short-circuits with **415 Unsupported Media Type** before the action runs. - **Source attributes inside a body model are ignored.** If `StockAdjustmentBatch` has a property marked `[FromQuery]`, the input formatter still fills it only from the JSON, because formatters do not understand binding-source attributes. - **Renaming.** `[FromRoute]`, `[FromQuery]`, `[FromForm]` and `[FromHeader]` all expose a `Name` property for a request key that differs from the C# name. - **Conversion failures.** `?dryRun=maybe` cannot convert to `bool`; the parameter keeps its default and `ModelState` gets an error for the key. ## What interviewers listen for - That `[FromBody]` uses an input formatter while the others use value providers or the header binder. - That headers and bodies are never bound implicitly in a plain controller. - That a JSON body to the wrong source silently yields defaults, not an exception. - That the stock-adjustment signature can be written from memory with the right `Name` on the header.

  • Why does [FromHeader] usually need its Name property?
    Without `Name`, MVC looks for a header with the C# parameter's own name, such as `correlationId`. Real header names like `X-Correlation-Id` contain hyphens that a C# identifier cannot, so `[FromHeader(Name = "X-Correlation-Id")]` maps the two. Header lookup is case-insensitive, so the casing the client sends does not matter.
  • A client posts the batch as form-urlencoded to the [FromBody] parameter; what response does it get?
    415 Unsupported Media Type. No input formatter accepts `application/x-www-form-urlencoded`, so the body binder adds an `UnsupportedContentTypeException` to `ModelState`, and MVC's default `UnsupportedContentTypeFilter` replaces the action result with `UnsupportedMediaTypeResult` before the action body runs.
  • Does a [FromQuery] attribute on a property of the [FromBody] model make that property come from the query string?
    No. When a parameter is bound with `[FromBody]`, the input formatter deserializes the whole object from the body and ignores binding-source attributes on its properties. If the value truly lives in the query string, declare it as its own `[FromQuery]` action parameter.

  • Any controller reads an unattributed complex parameter from the JSON body automatically.
  • Request headers bind by name without [FromHeader], just like query string keys.
  • [FromQuery] on a property inside a [FromBody] model pulls that property from the URL.
  • Posting form data to a [FromBody] parameter is converted to the model automatically.
  • [FromRoute] falls back to the query string when the route value is missing.