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.
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
