📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you bind your own types from a request in ASP.NET Core? Show TryParse and BindAsync for Minimal APIs and a custom model binder for controllers, using a strongly typed ID and a comma-separated list as examples, and explain when each is appropriate.

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.

Mid-Level Coding Intermediate aspnet-core custom-model-binder iparsable minimal-apis model-binding strongly-typed-ids

🎯 Key points

  • A type with static TryParse(string, IFormatProvider?, out T) (IParsable<T>) binds from route, query and headers in both Minimal APIs and MVC (.NET 7+)
  • Strongly typed IDs as readonly record structs with TryParse prevent mixing OrderId and CustomerId
  • static ValueTask<T?> BindAsync(HttpContext, ParameterInfo) builds a Minimal API parameter from several request parts
  • MVC custom IModelBinder + IModelBinderProvider (or [ModelBinder]) for complex cases; it records errors in ModelState and [ApiController] turns them into a 400
  • Binding source attributes still apply to custom types: [FromQuery], [FromRoute], [FromHeader] choose where the string comes from, and a binder controls how it is converted
  • Comma-separated lists: a wrapper type with TryParse works in both models; arrays bind from repeated keys (?id=1&id=2) by default
  • Body properties need a JsonConverter, not a model binder; binding and serialisation are separate
  • Binders and TryParse must stay cheap and side-effect free: no database calls, bounded input sizes

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 TryParse on the type, and from .NET 7 implementing IParsable<T>. Minimal APIs look for TryParse when they treat a parameter as a simple type, and MVC's TryParseModelBinder does the same, so one method works everywhere. That's how I do strongly typed IDs: a readonly record struct OrderId(Guid Value) with TryParse, so the compiler stops anyone passing a CustomerId where an OrderId is 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 custom IModelBinder registered through an IModelBinderProvider or [ModelBinder(typeof(...))]. It gets a ModelBindingContext, reads value providers, and calls ModelState.TryAddModelError on failure, so [ApiController] turns it into a proper 400.

For example, [at company] we had [an orders API] where /orders?ids=1,2,3 was split by hand in [a dozen] actions with inconsistent error handling. I added an IdList type with TryParse that 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 a JsonConverter. Binding and serialisation are different pipelines."


Choosing a mechanism

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

OpenAPI and validation impact

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

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate can extend binding cleanly and knows the boundary between binding and serialisation.

Green flags

  • Uses IParsable<T>/TryParse for IDs and lists, and knows it works in MVC since .NET 7.
  • Uses BindAsync only for multi-part Minimal API parameters.
  • Knows model binders are MVC-only and record ModelState errors.
  • Mentions JSON converters, EF converters and bounds on lists.

Red flags

  • Writes a model binder for everything.
  • Expects binders to affect JSON bodies.
  • Throws from TryParse or ignores invalid list items.

📚 Learn in depth

1. How the frameworks decide

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.

2. Accepted signatures

  • 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)
  • The type can implement IBindableFromHttpContext<T> (.NET 7+) to get compile-time checking of BindAsync.

3. Model binders

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.

4. Strongly typed IDs end to end

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.

5. Arrays and lists

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.

Try it yourself

  1. Create OrderId with IParsable<OrderId> and bind it in a Minimal API and a controller.
  2. Call the endpoint with an invalid value in Development and Production and compare responses.
  3. Implement BindAsync for a PageRequest that reads page, size and an X-Max-Page-Size header.
  4. Write a model binder for IdList and compare it with the TryParse version.
  5. Return OrderId in a response without a JsonConverter and see the JSON shape; add one and compare.

💻 Code

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
}

⚠ Common mistakes

  • Mistake: Writing a custom model binder for a simple string-convertible type. Why it is wrong: It only works in MVC and duplicates what TryParse gives you in both models. Instead: Implement IParsable<T>.
  • Mistake: Expecting a model binder or 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>.
  • Mistake: Calling the database from a model binder, 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.
  • Mistake: Unbounded lists from the query string. Why it is wrong: ?ids= with 50,000 values creates a huge IN clause or parameter list. Instead: Enforce a maximum in TryParse.
  • Mistake: Silently skipping invalid items in a list. Why it is wrong: The client thinks all items were processed. Instead: Fail the whole parse so the client gets a 400.
  • Mistake: Throwing from TryParse. Why it is wrong: It turns a 400 into a 500. Instead: Return false.
  • Mistake: Removing [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.
  • Mistake: Strongly typed IDs without JSON converters, EF Core value converters and OpenAPI schemas. Why it is wrong: Responses, persistence or the OpenAPI document break. Instead: Add converters and a schema transformer, or use a generator.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions TryParse making a type 'simple'. Why: Checks the inference rules that decide whether a custom type is treated as simple or complex.
    How to answer

    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.

  2. When: Candidate contrasts BindAsync with IModelBinder. Why: Checks how binding extensibility differs between Minimal APIs and controllers.
    How to answer

    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.

🛠 Real-world problems: how you handle them

Hand-split comma-separated IDs silently dropped invalid values
Situation
An orders API [at company] exposed `GET /orders?ids=1,2,3` used by [a warehouse dashboard]. Each of [about a dozen] actions split the string by hand with `int.TryParse` in a loop.
Signals
Warehouse staff reported missing orders on screen; logs showed requests like `ids=101,10 2,103` returning two orders with status 200; one action threw a 500 on an empty string while others returned all orders.
Investigation
Searched the codebase for `.Split(',')` on query values and found inconsistent handling; reproduced each variant with integration tests; checked Application Insights for request sizes and found requests with over [2,000] IDs causing slow SQL.
Resolution
Introduced an `IdList` type implementing `IParsable<IdList>` that trims, validates every value, caps the list at 100 and returns false on any error, so the framework returns a 400. Replaced the hand-written parsing in every action.
Prevention
Unit tests for `IdList` edge cases, an integration test per endpoint with invalid input, a code review rule against manual query parsing, and an OpenAPI description of the format.

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.

↩ Usually asked after

More in Request Handling

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me