liveBook · Manning

FromBody attribute

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

The FromBody attribute is an ASP.NET Core parameter-binding attribute that specifies binding a parameter from the deserialized HTTP request body.

The [FromBody] attribute tells ASP.NET Core to read a parameter from the HTTP request body and deserialize JSON into its type. It overrides the framework’s usual binding conventions. section 7.3 section 7.2

Bind a list of photos

public void OnPost([FromHeader] string userId, [FromBody] List<Photo> photos) { /* use photos */ }\n\nA JSON request body is deserialized into the photos parameter, while userId comes from the request header. section 16.2.3

Use [FromBody] with these behaviors in mind:

  • Razor Pages requires [FromBody] for JSON body binding; minimal APIs commonly infer the body source for complex parameters. section 16.2.3 section 7.3
  • Apply it to simple types when you deliberately want body binding instead of route or query-string binding. section 7.3
  • Avoid body binding on GET and similar verbs; unusual requests can fail at runtime and may confuse API consumers. section 7.3
  • Allow only one eligible complex body parameter, or the application can throw when it receives a request. section 7.3
  • Expect a 415 Unsupported Media Type response when the request body is not accepted JSON in the described configuration. section 7.3
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 */
    }
}

Inspect the complete handler signature to see body binding used alongside an explicitly selected header source. section 16.2.3

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

How deep it goes
Explains JSON deserialization, binding-source precedence, media-type failures, verb restrictions, and multiple-body-parameter errors.
Examples
Uses a Product record in a POST endpoint and a List<Photo> parameter in a Razor Pages handler.
What it assumes
Assumes familiarity with C# parameters and HTTP requests while teaching binding sources and JSON body handling.
What you can do after
Apply it via ASP.NET Core handler parameters to select JSON body binding and avoid common request-shape errors.
How it connects
Connects model binding with JSON deserialization, minimal APIs, Razor Pages, input formatters, and validation.

Also explained in

Compare how 2 books explain FromBody attribute →

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.