liveBook · Manning

BindAsync

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

BindAsync is a static method convention that allows an ASP.NET Core minimal API parameter type to define custom model-binding logic.

BindAsync lets a parameter type define custom model-binding logic for ASP.NET Core minimal APIs. The method receives HttpContext and returns the bound value, keeping request parsing inside the type. section 7.11 section 7.7

Use BindAsync when the built-in binding conventions do not match the request format:

  • Implement either BindAsync(HttpContext) or BindAsync(HttpContext, ParameterInfo); the simpler signature is usually sufficient. section 7.7
  • Read and parse request data through HttpContext, then return the constructed parameter value. section 7.7
  • Return null when parsing fails for a required parameter so minimal APIs produce a 400 Bad Request response. section 7.7
  • Remember that BindAsync is checked after explicit binding attributes and well-known types, but before TryParse, service injection, and JSON body binding. section 7.8

Parse a two-line size value

Map POST /sizes to a handler accepting SizeDetails. Define SizeDetails as a record with height and width, then implement its static async BindAsync method to read two lines from the request body and return null when either line is missing. A valid body containing two double values becomes a SizeDetails instance; an invalid required value produces a 400 response. section 7.7

public static ValueTask<T?> BindAsync(HttpContext context);
public static ValueTask<T?> BindAsync( 
HttpContext context, ParameterInfo parameter);

Compare the two supported BindAsync signatures before choosing the parameter metadata overload. section 7.7

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

How deep it goes
Explains signatures, request parsing, binding precedence, and 400-versus-500 failure behavior without detailing framework internals.
Examples
Demonstrates SizeDetails parsing two double values from separate request-body lines.
What it assumes
Assumes familiarity with minimal API handlers and HttpContext while demonstrating custom binding from the request body.
What you can do after
Build it from scratch by defining a parameter type that parses custom request data and returns a bound value or null.
How it connects
Connects custom model binding with HttpContext, binding sources, TryParse, dependency injection, and JSON body binding.

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.