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

📚 Interview question

How does model binding work in ASP.NET Core? Explain the binding sources ([FromRoute], [FromQuery], [FromBody], [FromHeader], [FromForm], [FromServices], [AsParameters]) and the rules each framework uses to infer the source when you don't specify one, in controllers versus Minimal APIs.

Model binding in ASP.NET Core: the binding source attributes, how controllers with [ApiController] and Minimal APIs infer sources for simple types, complex types, services and special types, the one-body rule, [AsParameters] parameter objects, and what happens when binding fails.

Junior Theory Intermediate aspnet-core controllers minimal-apis model-binding request-handling

🎯 Key points

  • Model binding maps HTTP request data (route, query, headers, form, body) and DI services to handler parameters
  • Explicit sources: [FromRoute], [FromQuery], [FromHeader], [FromForm], [FromBody], [FromServices]; [FromKeyedServices("key")] picks one of several registrations of the same service type
  • Minimal APIs infer: route if the name is in the template, otherwise query for simple types; registered services from DI; complex types from the JSON body; complex types bind from a form only with [FromForm] (.NET 8+)
  • [ApiController] infers [FromBody] for complex types, [FromForm] for IFormFile, [FromRoute] for route names, services for registered DI types (.NET 7+) and [FromQuery] for the rest
  • A handler can have many parameters from route, query, headers and DI, but only one bound from the body, because the body is a stream read once
  • HttpContext, HttpRequest, CancellationToken, ClaimsPrincipal are special types bound without attributes; [AsParameters] groups many parameters into one record
  • If binding fails in Minimal APIs the handler is not called and the client gets a 400 (an exception in Development); in controllers errors go to ModelState and [ApiController] returns 400 before the action
  • Without [ApiController], invalid or unbound models still reach the action with default values unless you check ModelState

⏱ 30-second 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.

🗣 Full answer (senior)

How I would answer this in an interview

"Model binding is the step that turns an HTTP request into typed method parameters. The framework looks at each parameter, decides where its value comes from, reads it as a string or stream, converts it, and passes it in. The sources are route values, the query string, headers, form fields, the request body, and the DI container.

You can always say where a value comes from with [FromRoute], [FromQuery], [FromHeader], [FromForm], [FromBody] or [FromServices]. When you don't, each model infers. Minimal APIs look at the route template first: if id appears in /orders/{id}, it's a route value. Other simple types, meaning anything with a TryParse, come from the query. If the type is registered in DI, it's a service. Special types like HttpContext, CancellationToken and ClaimsPrincipal are injected directly. Any remaining complex type is read from the JSON body. Controllers with [ApiController] are similar: complex types from the body, IFormFile from the form, names in the route template from the route, everything else from the query. Without [ApiController], complex types bind from form and query instead, which surprises people. Only one parameter can come from the body, because the body is a stream you read once. When a handler has lots of query parameters, I use [AsParameters] with a record so the signature stays readable.

The mistake I see is relying on inference in a way that silently changes behaviour, like registering a type in DI that was previously bound from the body. I'm explicit on public contracts. Binding is part of your API contract, so I make the source obvious."


Binding sources

Attribute Reads from Typical use
[FromRoute] Route values /orders/{id}
[FromQuery] Query string ?page=2&size=50
[FromHeader] Request headers X-Correlation-Id, If-Match
[FromForm] Form fields and files HTML forms, IFormFile
[FromBody] Request body (JSON by default) Commands, DTOs
[FromServices] / [FromKeyedServices] DI container Services in handlers or actions
[AsParameters] (Minimal APIs) Members bound individually Grouping many parameters

Inference rules

Parameter Minimal APIs [ApiController] controllers
Name matches route template Route Route
Simple type (has TryParse) Query Query
Registered DI service Service Needs [FromServices] (inferred for registered services since .NET 7)
Complex type JSON body JSON body
IFormFile / IFormFileCollection Form Form
HttpContext, CancellationToken, ClaimsPrincipal Special binding Via HttpContext or parameters

Production example

A search endpoint with 11 query parameters became ([AsParameters] ProductSearch search, IProductStore store, CancellationToken ct). The OpenAPI document didn't change, the handler went from a 15-line signature to 3 parameters, and adding a new filter became a one-line change to the record.

🔍 What the interviewer is checking

Checks that the candidate knows where each parameter value comes from and why binding sometimes 'mysteriously' fails.

Green flags

  • Lists binding sources and the inference rules for both models.
  • Knows only one body parameter is allowed and why.
  • Mentions [AsParameters], special types and the Content-Type requirement.
  • Binds to DTOs, not entities.

Red flags

  • Thinks complex types bind from the query by default.
  • Doesn't know what [ApiController] changes.
  • Uses entities as request models.

📚 Learn in depth

1. Where binding happens

Request ─► Routing (route values) ─► Endpoint
                                        │
             Minimal API: generated RequestDelegate binds each parameter, then calls handler
             MVC: action invoker ─► model binders + value providers ─► ModelState ─► action
  • Minimal APIs: RequestDelegateFactory (runtime) or the Request Delegate Generator (compile time) emits code per parameter: read RouteValues["id"], call int.TryParse, or ReadFromJsonAsync<T>. No ModelState.
  • MVC: value providers (route, query, form, header) expose key/value data; model binders (SimpleTypeModelBinder, ComplexObjectModelBinder, BodyModelBinder, FormFileModelBinder) build objects and record errors in ModelState.

2. Simple vs complex types

A type is "simple" if it can be converted from a single string: primitives, Guid, DateTime, enums, and any type with static bool TryParse(string, out T) (or IParsable<T>). Complex types in Minimal APIs come from the body unless you use [FromQuery] on a type with TryParse, [AsParameters], or BindAsync.

3. The body

The request body is a forward-only stream. Minimal APIs and BodyModelBinder read it once with System.Text.Json (using JsonOptions, web defaults: camelCase, case-insensitive). A second [FromBody] parameter is an error at start-up in Minimal APIs. Content type matters: Minimal APIs require application/json for body binding and return 415 otherwise.

4. Failure behaviour

  • Minimal APIs: a required parameter missing or unparsable gives a 400. With RouteHandlerOptions.ThrowOnBadRequest (on by default in Development) you get an exception with a clear message instead, which is great for debugging.
  • Controllers: errors go into ModelState; [ApiController] turns invalid ModelState into a 400 ValidationProblemDetails. Without it, the action runs with default values.

5. Nullability

In Minimal APIs nullability drives "required": int id is required, int? page and string? sort are optional, and parameters with default values are optional.

Try it yourself

  1. Write MapGet("/orders/{id}", (int id, int? page, IOrderStore store) => ...) and test /orders/abc in Development and Production.
  2. Post JSON with Content-Type: text/plain to a Minimal API and read the 415.
  3. Add two complex parameters to a Minimal API without attributes and read the start-up error.
  4. Remove [ApiController] from a controller and post JSON to an action taking a DTO; inspect the bound values.
  5. Replace six query parameters with [AsParameters] and diff the OpenAPI document.

💻 Code

Explicit and inferred binding in Minimal APIs, [AsParameters], and the controller equivalent.

// Program.cs
using Microsoft.AspNetCore.Mvc;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped<IProductStore, SqlProductStore>();
builder.Services.AddControllers();
var app = builder.Build();

// id: route (name in template); includeArchived: query (simple type); store: DI; ct: special
app.MapGet("/products/{id:int}", async (int id, bool includeArchived, IProductStore store, CancellationToken ct) =>
    await store.FindAsync(id, includeArchived, ct) is { } p ? Results.Ok(p) : Results.NotFound());

// Complex type with no attribute: JSON body. Header made explicit because it's part of the contract.
app.MapPost("/products", async (CreateProduct cmd, [FromHeader(Name = "Idempotency-Key")] string? key,
                                IProductStore store, CancellationToken ct) =>
{
    var product = await store.AddAsync(cmd, key, ct);
    return Results.Created($"/products/{product.Id}", product);
});

// [AsParameters]: each member bound individually (query by default), keeps the signature small
app.MapGet("/products", (
    [AsParameters] ProductSearch search, IProductStore store, CancellationToken ct) => store.SearchAsync(search, ct));

app.MapControllers();
app.Run();

public sealed record ProductSearch(string? Q, string? Category, decimal? MinPrice, int Page = 1, int Size = 20);
public sealed record CreateProduct(string Name, decimal Price);
public sealed record Product(int Id, string Name, decimal Price);

public interface IProductStore
{
    Task<Product?> FindAsync(int id, bool includeArchived, CancellationToken ct);
    Task<Product> AddAsync(CreateProduct cmd, string? idempotencyKey, CancellationToken ct);
    Task<IReadOnlyList<Product>> SearchAsync(ProductSearch search, CancellationToken ct);
}

// Controller equivalent: [ApiController] infers [FromRoute] for id and [FromBody] for the DTO
[ApiController]
[Route("api/products")]
public sealed class ProductsController(IProductStore store) : ControllerBase
{
    [HttpGet("{id:int}")]
    public async Task<ActionResult<Product>> Get(int id, [FromQuery] bool includeArchived, CancellationToken ct)
        => await store.FindAsync(id, includeArchived, ct) is { } p ? p : NotFound();

    [HttpGet]
    public Task<IReadOnlyList<Product>> Search([FromQuery] ProductSearch search, CancellationToken ct)
        => store.SearchAsync(search, ct); // complex type from the query needs [FromQuery] explicitly
}

⚠ Common mistakes

  • Mistake: Expecting a complex type to bind from the query string by default. Why it is wrong: Both Minimal APIs and [ApiController] read complex types from the body. Instead: Use [FromQuery] (controllers) or [AsParameters] (Minimal APIs).
  • Mistake: Two [FromBody] parameters. Why it is wrong: The body is a stream read once; Minimal APIs fail at start-up and MVC only binds one. Instead: Wrap both in one request DTO; other parameters can still come from route, query, headers or DI.
  • Mistake: Posting a multipart form to a Minimal API expecting a DTO to bind. Why it is wrong: Complex types bind from JSON unless marked [FromForm], so you get a 415. Instead: Add [FromForm] and, for browser forms, handle anti-forgery.
  • Mistake: Removing [ApiController] and expecting the same behaviour. Why it is wrong: Without it, complex types bind from form and query instead of the body, and an invalid model no longer triggers the automatic 400: the action runs with nulls or default values and only ModelState.IsValid tells you something went wrong. Instead: Keep it on API controllers, or add explicit attributes and check ModelState.
  • Mistake: Sending JSON with the wrong Content-Type. Why it is wrong: Minimal APIs return 415; MVC can't find a formatter. Instead: Send application/json and check client defaults.
  • Mistake: Making route parameters optional by type only in controllers. Why it is wrong: The template decides whether the route matches; int? id doesn't help if the template needs {id}. Instead: Use {id?} in the template.
  • Mistake: Binding directly to EF entities. Why it is wrong: Clients can set properties they shouldn't (over-posting). Instead: Bind to request DTOs and map.

🏛 Senior insight: trade-offs

Binding is part of the API contract, and a senior treats the inference rules as a convenience, not a design. On public APIs, explicit attributes (or [AsParameters] records) make the source visible in code reviews and in the OpenAPI document, and protect you from accidental changes, such as a DTO type later being registered in DI. The framework already gives you good failure behaviour: 400s in Minimal APIs, ModelState in MVC, and very readable exceptions in Development.

Option When it fits Cost When not to
Inference Internal APIs, obvious shapes Hidden rules Public contracts with mixed sources
Explicit [FromX] Public APIs, headers, ambiguous cases Slightly noisier signatures Trivial handlers
[AsParameters] record Many query/header parameters One more type One or two parameters
Custom BindAsync / model binder Your own types from several sources Code to maintain When TryParse is enough

🔗 Follow-ups the interviewer may ask

  1. When: Candidate contrasts binding rules between the two models. Why: Checks the wider differences between Minimal APIs and controllers beyond binding.
    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.

  2. When: Candidate mentions [ApiController] inference. Why: Checks what else [ApiController] changes, such as automatic 400s.
    How to answer

    In MVC, a controller is a class whose public methods are actions; each action becomes an endpoint and returns an action result (IActionResult, or ActionResult<T> for a typed body plus status codes). API controllers derive from ControllerBase; Controller adds view support. [ApiController] makes API behaviour explicit: attribute routing is required, an invalid ModelState returns an automatic 400 ValidationProblemDetails, binding sources are inferred (complex types from the body), and error status codes become ProblemDetails. For server-rendered UI there are two styles: MVC with Razor Views (a controller picks a .cshtml view) and Razor Pages (a .cshtml page with its own PageModel and OnGet/OnPost handlers). Razor Pages fits page-per-task, form-heavy apps; MVC fits when one controller serves many views or shares logic with APIs.

↩ Usually asked after

More in Request Handling

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me