liveBook · Manning

FromHeader attribute

As explained in ASP.NET Core in Action, 3e

The FromHeader attribute is an ASP.NET Core parameter-binding attribute that specifies binding a parameter from an HTTP header value.

The [FromHeader] attribute tells ASP.NET Core to bind a handler or page-handler parameter from an HTTP request header. It overrides the framework’s usual binding conventions, making the header source explicit. section 7.2 section 16.2.3

Binding a named header in a minimal API

Add Microsoft.AspNetCore.Mvc and decorate the parameter with [FromHeader]. The Name property maps the parameter to a differently named header: using Microsoft.AspNetCore.Mvc; app.MapGet("/products/{id}/paged", ([FromRoute] int id, [FromQuery] int page, [FromHeader(Name = "PageSize")] int pageSize) => $"Received id {id}, page {page}, pageSize {pageSize}"); A request containing the PageSize header supplies pageSize. Route and query values can often bind by convention, but header binding requires [FromHeader]. section 7.2

Listing 16.5 Choosing a binding source for model binding
public class PhotosModel: PageModel
{
    public void OnPost(
        [FromHeader] string userId,       #1
        [FromBody] List<Photo> photos)    #2
    {
        /* method implementation */
    }
}

Compare header binding in Razor Pages, where [FromHeader] can sit beside [FromBody] for a JSON request payload. section 16.2.3

In Razor Pages, applying [FromHeader] to a parameter such as userId binds the value from a header with that name. Use [FromBody] separately when JSON must be read from the request body. Validate bound values for formatting, expected values, and business rules. section 16.2.3 section 7.11

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains explicit source selection, named headers, and related body binding, but does not descend into binder internals.
Examples
Uses a paged products endpoint with id, page, and PageSize values, plus a Razor Pages handler receiving userId and photos.
What it assumes
Assumes familiarity with HTTP requests and handler parameters while demonstrating source selection through minimal API and Razor Pages examples.
What you can do after
Apply it via ASP.NET Core attributes to bind named or same-named request headers to handler parameters.
How it connects
Connects HTTP headers with model binding, minimal APIs, Razor Pages, route parameters, query strings, and JSON request bodies.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.