Coding question on custom binding: IParsable/TryParse for simple types such as strongly typed IDs, static BindAsync for types built from several request parts, custom IModelBinder and IModelBinderProvider for MVC (comma-separated lists), TypeConverter, JSON converters for body properties, and how each affects OpenAPI and validation.
It depends on where the value comes from. For a value in the route, query or a header, give the type a static TryParse (ideally implement IParsable<T>): both Minimal APIs and MVC (since .NET 7) then bind it like an int, which is perfect for strongly typed IDs like OrderId or a comma-separated list wrapper. When a Minimal API parameter needs several parts of the request (headers plus query, or the user), use static BindAsync(HttpContext, ParameterInfo). For controllers with complex rules, write a custom IModelBinder with an IModelBinderProvider, which records errors in ModelState. If the type is inside the JSON body, none of these apply: you need a JsonConverter. The trade-off: TryParse is simplest and portable across both models; binders give full control but only work in MVC.
"I start by asking where the value lives. If it's a single string in the route, query or a header, the cleanest option is a static
TryParseon the type, and from .NET 7 implementingIParsable<T>. Minimal APIs look forTryParsewhen they treat a parameter as a simple type, and MVC'sTryParseModelBinderdoes the same, so one method works everywhere. That's how I do strongly typed IDs: areadonly record struct OrderId(Guid Value)withTryParse, so the compiler stops anyone passing aCustomerIdwhere anOrderIdis expected, and/orders/{id}binds straight to it.When a parameter needs more than one string, say a paging object built from query values and a header, or a tenant context from a claim, Minimal APIs support
static ValueTask<T?> BindAsync(HttpContext context, ParameterInfo parameter). In controllers the equivalent is a customIModelBinderregistered through anIModelBinderProvideror[ModelBinder(typeof(...))]. It gets aModelBindingContext, reads value providers, and callsModelState.TryAddModelErroron failure, so[ApiController]turns it into a proper 400.For example, [at company] we had [an orders API] where
/orders?ids=1,2,3was split by hand in [a dozen] actions with inconsistent error handling. I added anIdListtype withTryParsethat splits on commas, rejects more than 100 IDs and invalid numbers, and returns false so the framework produces a 400. That removed the duplication and fixed [a bug where one invalid ID silently dropped the rest]. The mistake I see is writing a model binder for something that's really a JSON body property, where you need aJsonConverter. Binding and serialisation are different pipelines."
| Value comes from | Minimal APIs | Controllers |
|---|---|---|
| One string (route/query/header) | TryParse / IParsable<T> |
TryParse (.NET 7+) or TypeConverter |
| Several request parts | static BindAsync |
Custom IModelBinder |
| JSON body property | JsonConverter<T> |
JsonConverter<T> |
Repeated query keys (?id=1&id=2) |
int[] / List<int> works by default |
Same |
Comma-separated (?ids=1,2,3) |
Wrapper type with TryParse |
Wrapper with TryParse or a model binder |
| Mechanism | OpenAPI shows | Errors |
|---|---|---|
TryParse |
String parameter (add schema transformer for format) | 400 (Minimal), ModelState (MVC) |
BindAsync |
Not described automatically | Return null / throw BadHttpRequestException |
IModelBinder |
Depends on metadata | ModelState errors |
Introducing strongly typed IDs with TryParse across 70 endpoints caught 3 bugs at compile time where a customer ID was passed to an order lookup; the tests had missed them because both were Guids and test data happened to reuse the same values.
Checks whether the candidate can extend binding cleanly and knows the boundary between binding and serialisation.
Green flags
IParsable<T>/TryParse for IDs and lists, and knows it works in MVC since .NET 7.BindAsync only for multi-part Minimal API parameters.ModelState errors.Red flags
TryParse or ignores invalid list items.Minimal APIs (RequestDelegateFactory / Request Delegate Generator) check each parameter type in order: special types, BindAsync, TryParse (string-convertible → route/query/header), DI service, then body. MVC uses model binder providers in order; TryParseModelBinderProvider (added in .NET 7) handles types with a suitable TryParse, before ComplexObjectModelBinderProvider.
public static bool TryParse(string? value, IFormatProvider? provider, out T result) (the IParsable<T> shape)public static bool TryParse(string? value, out T result)public static ValueTask<T?> BindAsync(HttpContext context, ParameterInfo parameter) or BindAsync(HttpContext context)IBindableFromHttpContext<T> (.NET 7+) to get compile-time checking of BindAsync.ModelBindingContext
├─ ValueProvider.GetValue(ModelName) (route, query, form, header providers)
├─ ModelState (record errors)
└─ Result = ModelBindingResult.Success(model) / Failed()
Providers are inserted into MvcOptions.ModelBinderProviders (usually at index 0 so they win). [ModelBinder(BinderType = ...)] targets a single parameter or type.
An ID type usually needs: TryParse (routes and query), a JsonConverter (bodies and responses), an EF Core value converter (persistence), and an OpenAPI schema transformer (so the document says string/uuid rather than an object). Source generators like StronglyTypedId or Vogen produce all of these.
By default int[] ids binds from repeated keys ?ids=1&ids=2. Comma-separated values aren't split by the framework, which is why a wrapper type is needed. Bound collections should have an upper bound to avoid huge queries.
OrderId with IParsable<OrderId> and bind it in a Minimal API and a controller.BindAsync for a PageRequest that reads page, size and an X-Max-Page-Size header.IdList and compare it with the TryParse version.OrderId in a response without a JsonConverter and see the JSON shape; add one and compare.A strongly typed ID and a comma-separated list with IParsable<T>, a BindAsync paging type, and an MVC custom model binder.
// Binding/Types.cs
using System.Diagnostics.CodeAnalysis;
using System.Reflection;
namespace Orders.Api.Binding;
// Binds from route/query/header in Minimal APIs AND MVC (TryParseModelBinder, .NET 7+)
public readonly record struct OrderId(Guid Value) : IParsable<OrderId>
{
public static OrderId Parse(string s, IFormatProvider? provider) =>
TryParse(s, provider, out var id) ? id : throw new FormatException($"Invalid order id '{s}'.");
public static bool TryParse([NotNullWhen(true)] string? s, IFormatProvider? provider, out OrderId result)
{
var ok = Guid.TryParse(s, out var guid) && guid != Guid.Empty;
result = ok ? new OrderId(guid) : default;
return ok; // never throw: false becomes a 400, an exception becomes a 500
}
public override string ToString() => Value.ToString();
}
// ?ids=1,2,3 : the framework does not split commas, so a wrapper type does
public sealed record IdList(IReadOnlyList<int> Values) : IParsable<IdList>
{
public const int MaxItems = 100;
public static IdList Parse(string s, IFormatProvider? provider) =>
TryParse(s, provider, out var list) ? list : throw new FormatException("Invalid id list.");
public static bool TryParse([NotNullWhen(true)] string? s, IFormatProvider? provider, [MaybeNullWhen(false)] out IdList result)
{
result = null;
if (string.IsNullOrWhiteSpace(s)) return false;
var parts = s.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
if (parts.Length > MaxItems) return false; // bound the query size
var values = new List<int>(parts.Length);
foreach (var part in parts)
{
if (!int.TryParse(part, provider, out var v) || v <= 0) return false; // one bad id fails the request
values.Add(v);
}
result = new IdList(values);
return true;
}
}
// BindAsync: built from several request parts (Minimal APIs only)
public sealed record PageRequest(int Page, int Size)
{
public static ValueTask<PageRequest?> BindAsync(HttpContext context, ParameterInfo parameter)
{
var q = context.Request.Query;
var max = int.TryParse(context.Request.Headers["X-Max-Page-Size"], out var m) ? Math.Min(m, 200) : 50;
var page = int.TryParse(q["page"], out var p) && p > 0 ? p : 1;
var size = int.TryParse(q["size"], out var s) && s > 0 ? Math.Min(s, max) : 20;
return ValueTask.FromResult<PageRequest?>(new PageRequest(page, size));
}
}
// Binding/DateRangeModelBinder.cs: MVC custom binder for a value split across two query keys
using Microsoft.AspNetCore.Mvc.ModelBinding;
namespace Orders.Api.Binding;
public sealed record DateRange(DateOnly From, DateOnly To);
public sealed class DateRangeModelBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext ctx)
{
var prefix = ctx.ModelName; // e.g. "period" -> period.from, period.to
var from = ctx.ValueProvider.GetValue($"{prefix}.from").FirstValue;
var to = ctx.ValueProvider.GetValue($"{prefix}.to").FirstValue;
if (!DateOnly.TryParse(from, out var f) || !DateOnly.TryParse(to, out var t))
{
ctx.ModelState.TryAddModelError(prefix, "Use period.from and period.to as yyyy-MM-dd.");
return Task.CompletedTask; // Failed: [ApiController] returns 400
}
if (t < f || t.DayNumber - f.DayNumber > 366)
{
ctx.ModelState.TryAddModelError(prefix, "The period must be between 1 and 366 days.");
return Task.CompletedTask;
}
ctx.Result = ModelBindingResult.Success(new DateRange(f, t));
return Task.CompletedTask;
}
}
public sealed class DateRangeModelBinderProvider : IModelBinderProvider
{
public IModelBinder? GetBinder(ModelBinderProviderContext context) =>
context.Metadata.ModelType == typeof(DateRange) ? new DateRangeModelBinder() : null;
}
// Program.cs: Minimal APIs and a controller using the same types
using Microsoft.AspNetCore.Mvc;
using Orders.Api.Binding;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers(o => o.ModelBinderProviders.Insert(0, new DateRangeModelBinderProvider()));
var app = builder.Build();
app.MapGet("/orders/{id}", (OrderId id) => TypedResults.Ok(new { id })); // invalid guid -> 400
app.MapGet("/orders", (IdList ids, PageRequest paging) => TypedResults.Ok(new { ids.Values, paging }));
app.MapControllers();
app.Run();
[ApiController, Route("api/orders")]
public sealed class OrdersController : ControllerBase
{
[HttpGet("{id}")]
public IActionResult Get([FromRoute] OrderId id) => Ok(new { id }); // source + TryParse conversion
[HttpGet]
public IActionResult List([FromQuery] IdList ids) => Ok(ids.Values); // invalid -> ModelState -> 400
[HttpGet("report")]
public IActionResult Report([FromQuery] DateRange period) => Ok(period); // ?period.from=2026-07-01&period.to=2026-09-30
}
TryParse gives you in both models. Instead: Implement IParsable<T>.TryParse to affect JSON body properties. Why it is wrong: Bodies are deserialised by System.Text.Json, a separate pipeline. Instead: Add a JsonConverter<T>.BindAsync or TryParse (for example to load the order for an OrderId). Why it is wrong: Binding runs before authorisation filters and validation, so unauthorised or invalid requests still cost a query; errors surface as confusing binding failures; and it can't be cancelled or cached cleanly. Instead: Bind identifiers only and load data in the handler after authorisation.?ids= with 50,000 values creates a huge IN clause or parameter list. Instead: Enforce a maximum in TryParse.TryParse. Why it is wrong: It turns a 400 into a 500. Instead: Return false.[ApiController] from controllers using custom binders. Why it is wrong: Binder errors land in ModelState but the action still runs with a null or default value. Instead: Keep [ApiController], or check ModelState.IsValid explicitly.Custom binding is where you encode domain types at the edge of the API: strongly typed IDs, money, date ranges, sort expressions. A senior chooses the most portable mechanism (IParsable<T> works in Minimal APIs, MVC, configuration binding and your own code) and remembers the whole life cycle of the type: route binding, JSON, EF Core and OpenAPI.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
IParsable<T> / TryParse |
Single-string values: IDs, lists, ranges | Tiny | Values from several request parts |
BindAsync |
Minimal API parameters from several parts | Not described in OpenAPI | Controllers |
IModelBinder |
MVC types needing value providers and ModelState control |
More code, MVC-only | When TryParse is enough |
JsonConverter<T> |
Types inside JSON bodies | Per-type converter | Route/query values |
| Source generator (Vogen, StronglyTypedId) | Many ID types | Dependency | One or two types |
Model binding takes data from the request (route values, query string, headers, form fields, the JSON body) and from DI, converts it, and passes it to your handler's parameters. You can be explicit with [FromRoute], [FromQuery], [FromHeader], [FromForm], [FromBody] and [FromServices], or let the framework infer. In Minimal APIs: a parameter named in the route template comes from the route, other simple types from the query, registered services from DI, and complex types from the JSON body. In controllers with [ApiController]: complex types from the body, IFormFile from the form, route names from the route, the rest from the query. Only one parameter can read the body. [AsParameters] groups parameters into a record. The trade-off: inference keeps code short, but explicit attributes make the contract obvious in reviews and OpenAPI.
Both sit on the same foundation: endpoint routing, middleware, DI, authentication and OpenAPI. The difference is the programming model. Minimal APIs map handlers directly with MapGet/MapPost, organise with route groups, return TypedResults, use endpoint filters, support Native AOT, and in .NET 10 get built-in DataAnnotations validation with AddValidation(). Controllers group actions in classes and bring the full MVC feature set: [ApiController] behaviours (automatic 400s, binding inference), the five MVC filter types, custom model binders, input/output formatters with content negotiation and JSON Patch. For a new API service I default to Minimal APIs organised by feature; I choose controllers when the team relies on MVC filters, formatters or existing conventions. The trade-off is less ceremony and AOT versus a richer, more conventional framework.
How to tell it (STAR)
**S:** Our [orders API] parsed comma-separated IDs by hand in [a dozen] actions, and the warehouse dashboard was silently missing orders. **T:** I owned fixing it consistently. **A:** I reproduced the variants with tests, then built an `IdList` type with `TryParse` that validates every value, caps the size and fails the whole request on bad input, and replaced all the hand-written parsing. **R:** Missing-order reports stopped, invalid requests now get a clear 400, and the slow queries from [2,000-ID] requests disappeared.
Last updated 23 Nov 2026.