liveBook · Manning

Custom binding

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

Custom binding is a model-binding technique in which application-defined methods control how a type is created from an HTTP request.

Custom binding lets an application control how a type is created from an HTTP request instead of relying on minimal API conventions. It is useful when the request data needs special handling, such as an arbitrary JSON upload. section 7.11 section 7.1

Implement custom binding by giving the bound type a static method with this shape:

  • public static ValueTask<T?> BindAsync(HttpContext context) section 7.11
  • Use the HttpContext to inspect the incoming request, create the application-defined type, and return the bound value. section 7.11
  • Choose custom binding when ordinary route, query, header, JSON-body, or dependency-injection binding does not express the required behavior. section 7.1

A suitable use case

An endpoint receiving arbitrary JSON can use a type’s BindAsync method to read the request and construct that type according to application rules. Validate the resulting data, including its format, allowed values, and business constraints. section 7.11

Figure 7.1 The RoutingMiddleware matches the incoming request to an endpoint and extracts the route parameters as strings. When the EndpointMiddleware executes the endpoint, the minimal API infrastructure uses model binding to create the arguments required to execute the endpoint handler, converting the string route values to real argument types such as int.
CH07_F01_Lock3

Compare custom binding with ordinary model binding: routing extracts route values as strings, then minimal API infrastructure converts them into handler argument types. section 7.1

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

How deep it goes
Defines the BindAsync signature and purpose but leaves its request-reading implementation to the application.
Examples
Uses arbitrary JSON uploads as the complex request scenario and contrasts them with route-value conversion.
What it assumes
Builds on minimal API handler parameters and HttpContext while distinguishing custom binding from built-in request sources.
What you can do after
Apply custom binding by implementing a static BindAsync method that returns the request-derived type.
How it connects
Connects model binding with HttpContext, JSON request bodies, dependency injection, and minimal APIs.

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.