In ASP.NET Core Minimal APIs, when do you give a custom type a static TryParse, and when a BindAsync or IBindableFromHttpContext<T> instead?
answer
- one string in, one value out
- IParsable<T>, InvariantCulture
- BindAsync sees the whole HttpContext
- BindAsync is checked before TryParse
- IBindableFromHttpContext<TSelf>: classes only
basics
~10 sUse TryParse when the value is one string from the route, query or a header; use BindAsync or IBindableFromHttpContext<T> when binding needs the whole HttpContext, such as several query keys, headers or async work.
solid answer
~40 sMinimal APIs treat any type with `static bool TryParse(string, out T)`, `TryParse(string, IFormatProvider, out T)` or an `IParsable<T>` implementation as a simple type: it binds from the route or query (or a header with `[FromHeader]`), ASP.NET Core passes `CultureInfo.InvariantCulture`, and a `false` return is a 400. A static `ValueTask<T?> BindAsync(HttpContext)` or `BindAsync(HttpContext, ParameterInfo)` takes over binding completely and is checked before `TryParse`; it can read several query keys, headers or claims. Returning `null` gives a 400 for a non-nullable parameter and passes `null` for a nullable one, while an exception it throws is not a binding failure and surfaces as an unhandled error. `IBindableFromHttpContext<TSelf>` is the same `BindAsync` as a static abstract interface member, constrained to classes, so a struct cannot use it.
go deeper
Recall that a static TryParse makes a custom type bindable from the route or query string just like int or Guid.
Explain the accepted TryParse and BindAsync signatures, their precedence, and the 400 rules for false and null.
Choose the hook per type, keep rejections as 400s rather than exceptions, and remember invariant culture when parsing numbers and dates.
Decide which domain types own their own parsing across services and how much request knowledge you let leak into those types through BindAsync.
## Two hooks for two shapes of input Minimal APIs have no `IModelBinder` and do not use `TypeConverter`. A custom type takes part in binding by exposing a **static method the binder looks for**, found once when the endpoint is built: | | `TryParse` | `BindAsync` / `IBindableFromHttpContext<TSelf>` | |---|---|---| | Input | one string (or one per array element) | the entire `HttpContext`, optionally the `ParameterInfo` | | Sources | route, query, header, simple form values | anything the request carries | | Signature | `static bool TryParse(string, out T)`, `TryParse(string, IFormatProvider, out T)`, or `IParsable<T>` | `static ValueTask<T?> BindAsync(HttpContext)` or `BindAsync(HttpContext, ParameterInfo)` | | Culture | `CultureInfo.InvariantCulture` is passed | you decide | | Failure | returns false: 400 | returns null: 400 if the parameter is non-nullable, else null | | Exception | n/a | propagates; it is not a binding failure | | Precedence | after `BindAsync` | before `TryParse` | ## TryParse: a value object from one string The recipe API lets clients sort with `?sort=rating:desc`. A small type parses it: ```csharp public readonly record struct RecipeSort(string Field, bool Descending) : IParsable<RecipeSort> { public static bool TryParse(string? s, IFormatProvider? provider, out RecipeSort result) { var parts = (s ?? "").Split(':'); result = new(parts[0], parts.Length > 1 && parts[1] == "desc"); return parts[0] is "rating" or "time" or "title"; } public static RecipeSort Parse(string s, IFormatProvider? provider) => TryParse(s, provider, out var r) ? r : throw new FormatException(); } app.MapGet("/recipes", (RecipeSort sort, IRecipeStore store) => store.List(sort)); ``` Because `RecipeSort` has `TryParse`, it is a **simple type**: it binds from the route if a `{sort}` segment exists, otherwise from the query string. Other points: - **Arrays** of the type (`RecipeSort[] sort`) bind from repeated query values on GET-family endpoints. - A `false` return makes the request a **400** even when the parameter is `RecipeSort?`; nullability only covers absence, not bad input. - Since `InvariantCulture` is passed, decimal or date parsing does not follow the server's locale. ## BindAsync: a value assembled from the request Paging needs two query keys, a cap and a header: ```csharp public sealed class PageRequest : IBindableFromHttpContext<PageRequest> { public int Page { get; init; } public int Size { get; init; } public static ValueTask<PageRequest?> BindAsync(HttpContext ctx, ParameterInfo parameter) { var q = ctx.Request.Query; int.TryParse(q["page"], out var page); int.TryParse(q["size"], out var size); if (ctx.Request.Headers.ContainsKey("X-Preview")) size = 5; return ValueTask.FromResult<PageRequest?>(new() { Page = Math.Max(page, 1), Size = Math.Clamp(size, 1, 50) }); } } ``` Points to remember: 1. `BindAsync` wins over `TryParse` if a type has both. 2. The two-argument form receives the handler's `ParameterInfo`, so one type can read the parameter's name or attributes. 3. Returning `null` is how you **reject** input: the binder logs "Required parameter ... was not provided" and answers 400 for a non-nullable parameter. 4. **Throwing** is not a rejection. The exception leaves the request delegate and is handled by the exception handler, normally as a 500. 5. `IBindableFromHttpContext<TSelf>` is declared `where TSelf : class, IBindableFromHttpContext<TSelf>`, so a **struct** must use the plain static `BindAsync` instead. ## Choosing - **One textual value** that maps to one domain value (an id, a slug, a sort spec, a date range string): `TryParse`. It stays usable in route templates, arrays and headers, and the type is reusable outside ASP.NET Core. - **Several request parts, async work or request services**: `BindAsync`. - **A plain group of route, query and header values** with no custom logic: neither; `[AsParameters]` is simpler. - **A wrong signature** is not ignored silently: the binder throws `InvalidOperationException` listing the signatures it expected. ## Keeping the hooks honest - **Unit-test them directly.** `RecipeSort.TryParse("rating:desc", CultureInfo.InvariantCulture, out var sort)` needs no web host, and a `BindAsync` can be exercised with a `DefaultHttpContext` whose query string you set. - **Keep `TryParse` pure.** It runs for every request that carries the value, on the request path, so it should not call services or do I/O; anything that needs a service belongs in `BindAsync` or in the handler. - **Remember the header and array cases.** The same `TryParse` serves `[FromHeader] RecipeSort sort` and `RecipeSort[] sort`, so its error handling must be right for both. - **Watch the type in the route.** A `TryParse` type named in a template segment changes nothing about matching: a value that fails to parse still matches the route and then fails binding with a 400. ## What interviewers listen for - The **single string versus whole context** distinction and the precedence of `BindAsync`. - **400 for false or null, not for an exception**. - `InvariantCulture` and the **class-only constraint** on `IBindableFromHttpContext<TSelf>`.
- What does a BindAsync that throws on a malformed header produce, and what should it do instead?The exception escapes the request delegate, so it is logged as an unhandled exception and turned into a 500 by the exception handler; the client is blamed for nothing. To reject bad input, return `null` from `BindAsync` for a non-nullable parameter, which the binder turns into a 400 with a "Required parameter ... was not provided" log entry, or return a value the handler validates.
- Why can't a readonly struct implement IBindableFromHttpContext<TSelf>?The interface constrains `TSelf` to `class`, so a struct does not satisfy it. A struct can still bind itself by declaring a public static `ValueTask<T?> BindAsync(HttpContext)` or `BindAsync(HttpContext, ParameterInfo)` method; the binder finds that by reflection. The interface only adds compile-time checking of the signature.
- Minimal APIs use a TypeConverter on the type to bind custom route values.
- Making a TryParse parameter nullable turns unparsable input into null instead of a 400.
- Throwing from BindAsync is the standard way to answer 400 Bad Request.
- TryParse is preferred over BindAsync when a type defines both.
- Implementing IModelBinder registers a custom binder for Minimal API handlers.