skip to content

In ASP.NET Core MVC, when is a custom IModelBinder with an IModelBinderProvider justified, and how do you register it so it runs before the built-in binders?

level: seniorimportance: should knowfreq 35%

answer

  1. prefer TypeConverter or IParsable first
  2. first provider returning non-null wins
  3. MvcOptions.ModelBinderProviders.Insert(0, ...)
  4. ValueProviderResult.None, ModelBindingResult.Success
  5. BinderTypeModelBinder for DI

basics

~20 s

Write one when a value cannot be produced by a TypeConverter or IParsable<T>.TryParse, such as a comma-separated list or a value assembled from several inputs. Register its provider with MvcOptions.ModelBinderProviders.Insert(0, ...), because the first provider returning a binder wins.

solid answer

~40 s

MVC asks each `IModelBinderProvider` in `MvcOptions.ModelBinderProviders`, in order, and uses the first binder returned. The built-ins cover simple types (through `TypeConverter` or `TryParse`), arrays, collections, dictionaries and complex objects, so for a single string-to-type conversion I would implement `IParsable<T>` first. A custom binder is justified for shapes the built-ins cannot express, such as `?skus=BOLT-M8,NUT-M8` into a `string[]`, or one model drawn from several inputs. The binder reads `ValueProvider.GetValue(ModelName)`, returns early on `ValueProviderResult.None`, records the raw value with `ModelState.SetModelValue`, and sets `ModelBindingResult.Success` or adds a `ModelState` error; it never returns a 404. The provider is inserted at index 0 with `AddControllers(o => o.ModelBinderProviders.Insert(0, ...))`, since appending it lets a built-in binder claim the type first. For one parameter, `[ModelBinder<TBinder>]` is simpler.

go deeper

for a junior

Know that MVC binders turn request values into parameters and that a custom one exists for shapes the defaults cannot handle.

for a middle

Explain the provider list, first non-null wins, and why IParsable<T> or a TypeConverter usually beats a custom binder for one string.

for a senior

Write a stateless binder that follows the ValueProviderResult and ModelState contract, register it at index 0, and use BinderTypeModelBinder for DI.

for a principal

Weigh app-wide binding conventions against per-parameter attributes, considering OpenAPI accuracy, discoverability and how surprising global binders are to new team members.

## How MVC picks a binder For every parameter and property it binds, ASP.NET Core MVC builds a **binder** by walking `MvcOptions.ModelBinderProviders`. Each `IModelBinderProvider.GetBinder(ModelBinderProviderContext)` either returns an `IModelBinder` or `null`, and **the first non-null result wins**. The default list starts with the providers for `[ModelBinder]` attributes, services, `[FromBody]` and headers, continues through floating-point, enum, date, simple-type and `TryParse` binders, cancellation tokens, byte arrays, form files and form collections, then key-value pairs, dictionaries, arrays and collections, and ends with the complex-object provider. Binders created by providers are cached per model metadata, so a binder instance is reused across requests and must be stateless. ## Try the cheaper extension points first | Need | Extension point | |---|---| | One string becomes one value (`"WH-12"` to `WarehouseCode`) | a `TypeConverter`, or `IParsable<T>.TryParse` on the type | | One parameter needs special binding | `[ModelBinder<TBinder>]` or `[ModelBinder(typeof(TBinder))]` on it | | A new place to read values from (a cookie, a claim) | an `IValueProvider` plus `IValueProviderFactory` | | A type or shape across the whole app | an `IModelBinderProvider` | The documentation recommends a type converter or `TryParse` for plain string conversions and keeps custom binders for removing repetitive, cross-cutting binding code. ## A comma-separated list binder The built-in collection binder understands `?skus=BOLT-M8&skus=NUT-M8` and indexed keys such as `skus[0]=BOLT-M8`, but not one comma-separated value. You cannot add `IParsable<T>` to `string[]`, so this is a fair custom binder: ```csharp public sealed class CsvQueryArrayBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext context) { var raw = context.ValueProvider.GetValue(context.ModelName); if (raw == ValueProviderResult.None) return Task.CompletedTask; // no value: Result stays unset context.ModelState.SetModelValue(context.ModelName, raw); var items = raw.Values .SelectMany(v => (v ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) .ToArray(); context.Result = ModelBindingResult.Success(items); return Task.CompletedTask; } } ``` The binder contract it follows: 1. Read through `context.ValueProvider` with `context.ModelName`; the value providers are already filtered to the parameter's binding source. 2. On `ValueProviderResult.None`, leave `Result` unset so MVC treats the value as missing. 3. Call `ModelState.SetModelValue` so errors and redisplay see the attempted value. 4. Report bad input with `ModelState.TryAddModelError` and `ModelBindingResult.Failed()`. A binder **should not set status codes**; the action or a filter decides on 400 or 404. ## Registering the provider ```csharp public sealed class CsvQueryArrayBinderProvider : IModelBinderProvider { public IModelBinder? GetBinder(ModelBinderProviderContext context) => context.Metadata.ModelType == typeof(string[]) && context.BindingInfo.BindingSource == BindingSource.Query ? new CsvQueryArrayBinder() : null; } builder.Services.AddControllers(options => options.ModelBinderProviders.Insert(0, new CsvQueryArrayBinderProvider())); ``` `Insert(0, ...)` matters: with `Add`, the built-in array provider answers for `string[]` first and the custom one is never asked. When a binder needs scoped services, return `new BinderTypeModelBinder(typeof(MyBinder))`; it creates the binder from `HttpContext.RequestServices` on each binding. ## Built-in collection limits - `MvcOptions.MaxModelBindingCollectionSize` defaults to **1024**; an indexed collection (`lines[0]`, `lines[1]`, ...) that grows past it makes the collection binder throw `InvalidOperationException`. - Indexed form keys must run from `[0]` without gaps unless the request lists them with `name.index` keys. - `MaxModelBindingRecursionDepth` defaults to **32** for nested models. ## What interviewers listen for - Knowing that most needs are met by `IParsable<T>`, a `TypeConverter` or `[ModelBinder]` before writing a provider. - The provider order and why `Insert(0, ...)` beats `Add`. - The binder contract: `ValueProviderResult.None`, `SetModelValue`, `ModelBindingResult`, no HTTP results. - Statelessness, because provider-built binders are cached.

  • Why should a custom model binder not return 404 when a looked-up entity is missing?
    A binder only produces a value or a binding failure; it has no HTTP result to return. Mixing lookups into binding blurs "the id was malformed" with "the stock item does not exist". The ASP.NET Core docs recommend binding the id and letting the action or a filter decide between 400 and 404.
  • How does a custom binder get a scoped service such as a DbContext safely?
    Return `new BinderTypeModelBinder(typeof(MyBinder))` from the provider, or put `[ModelBinder<MyBinder>]` on the parameter. `BinderTypeModelBinder` builds the binder with `ActivatorUtilities` from `HttpContext.RequestServices` on each binding, so constructor dependencies come from the request scope. A binder instance created directly by a provider is cached and must not capture scoped services.
  • What does MVC do when an indexed collection binding exceeds 1024 items?
    When binding indexed keys such as `lines[0]`, `lines[1]`, the collection binder checks `MvcOptions.MaxModelBindingCollectionSize`, 1024 by default, and throws `InvalidOperationException` once the collection grows past it. The limit guards against runaway binders and huge payloads; raise it in `AddControllers` options if a legitimate form posts more rows.

  • Appending a provider with ModelBinderProviders.Add makes it run before the built-in binders.
  • A custom binder should return NotFound when the referenced entity does not exist.
  • Every new string-to-type conversion needs a custom IModelBinder.
  • A provider-created binder may keep per-request state in fields.
  • The default collection binder already splits comma-separated query values.