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

📚 Interview question

Minimal APIs or controllers? Compare them on features, filters, model binding, validation, testability and performance in .NET 10, and tell me how you would choose for a new service.

Minimal APIs versus MVC controllers in .NET 10: programming model, binding and validation differences (built-in Minimal API validation in .NET 10), endpoint filters versus MVC filters, conventions, OpenAPI, Native AOT support, testability and how to choose.

Junior Theory Intermediate api-design aspnet-core controllers minimal-apis mvc

🎯 Key points

  • Both run on the same endpoint routing, middleware, DI, auth and OpenAPI infrastructure; the difference is the programming model
  • Minimal APIs map lambdas or methods to routes with MapGet/MapPost; controllers group actions in classes discovered by convention
  • Both now validate automatically: controllers via [ApiController] and ModelState, Minimal APIs in .NET 10 via AddValidation() (DataAnnotations, ProblemDetails 400)
  • Controllers keep MVC-only features: five MVC filter stages, custom model binders and value providers, formatters with content negotiation, JSON Patch
  • Minimal APIs have endpoint filters, route groups and TypedResults, and support Native AOT through the Request Delegate Generator; MVC controllers do not
  • Minimal APIs are slightly faster and lighter; for I/O-bound APIs the difference is rarely the bottleneck
  • Maintainability depends on structure (feature folders, route groups, conventions), not the style
  • Choose per service for consistency; migrate existing controller APIs incrementally only when there is a concrete benefit such as AOT

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

🗣 Full answer (senior)

How I would answer this in an interview

"The first thing to say is that they are not two frameworks. Since .NET 6, Minimal APIs and controllers both produce endpoints in the same routing system, run through the same middleware, use the same DI container, authorisation policies and OpenAPI generation. So the decision is about the programming model and a few features, not performance or capability in general.

Minimal APIs map a handler straight to a route. Parameters are bound from route, query, headers, body or DI by inference, I return TypedResults so the response types are known at compile time and show up in OpenAPI, and I organise them with MapGroup and one extension method per feature. Cross-cutting logic goes in endpoint filters. They work with Native AOT through the Request Delegate Generator, and since .NET 10, builder.Services.AddValidation() validates DataAnnotations on parameters and returns a ProblemDetails 400 automatically, which closed the biggest gap. Controllers give the full MVC stack: [ApiController] with automatic 400s and binding source inference, authorisation, resource, action, exception and result filters, custom model binders and value providers, input and output formatters with content negotiation, and JSON Patch.

For a new HTTP API I default to Minimal APIs with feature folders. I choose controllers if the team already has a large MVC codebase, needs XML or other formatters, or relies on filters like resource filters. The mistake I see is turning this into a religious debate or writing Minimal APIs as one 2,000-line Program.cs. Structure matters far more than which style you pick."


Side by side

Minimal APIs Controllers
Definition app.MapGet("/orders/{id}", handler) [HttpGet("{id}")] action in a ControllerBase class
Organisation Route groups, extension methods per feature Classes, areas, conventions
Validation .NET 10 AddValidation() (DataAnnotations), endpoint filters, FluentValidation [ApiController] automatic 400 from ModelState
Cross-cutting Endpoint filters (IEndpointFilter) Five MVC filter types
Binding Inference + [AsParameters], TryParse/BindAsync Model binders, value providers, [FromX]
Output TypedResults, JSON by default Formatters, content negotiation (JSON, XML)
Native AOT Supported Not supported
Testing Handlers as static methods; WebApplicationFactory Controller unit tests; WebApplicationFactory

How I choose

Situation Choice
New microservice or BFF, small team Minimal APIs
Native AOT or serverless cold start matters Minimal APIs
Large existing MVC API, shared filters Controllers
Needs XML/custom formatters or JSON Patch Controllers
Server-rendered UI Razor Pages or MVC views (not this question)

Production example

A team migrating a 60-endpoint internal API from controllers to Minimal APIs measured roughly 10–15% higher requests per second in a synthetic benchmark, but no change in p95 latency in production because every request spent 30+ ms in SQL. The real win was start-up time under Native AOT (from about 1.5 s to under 200 ms), which mattered for scale-to-zero on Azure Container Apps.

🔍 What the interviewer is checking

Checks whether the candidate understands both models and chooses based on facts rather than fashion.

Green flags

  • States they share routing, middleware and DI.
  • Names concrete differences: filters, formatters, [ApiController], AOT, .NET 10 validation.
  • Talks about structure (route groups) for Minimal APIs.
  • Gives a clear default with reasons.

Red flags

  • 'Minimal APIs are for prototypes only.'
  • Picks based on performance without measurement.
  • Unaware of endpoint filters or route groups.

📚 Learn in depth

1. Same endpoints underneath

MapGet(...)          ─┐
MapControllers()     ─┼─► EndpointDataSource ─► DFA matcher ─► RequestDelegate per endpoint
MapRazorPages()      ─┘

A controller action becomes an endpoint whose RequestDelegate runs the MVC action invoker: it creates the controller, runs the filter pipeline, model binding, validation and result execution. A Minimal API handler becomes an endpoint whose RequestDelegate is generated by RequestDelegateFactory (runtime, using expression trees) or the Request Delegate Generator (compile time, source-generated, required for Native AOT). That generated delegate does binding and result writing directly, which is why it is lighter.

2. Binding differences

  • Minimal APIs: simple types from route, then query; complex types from the body (JSON only); services detected from DI; HttpContext, CancellationToken, ClaimsPrincipal injected specially. Custom types bind via static TryParse or static BindAsync. [AsParameters] groups parameters into a record.
  • Controllers: model binders and value providers, [FromForm], [FromHeader], custom IModelBinder, binding of complex types from query strings, and [ApiController] source inference.

3. Validation

  • Controllers: model binding populates ModelState; [ApiController] short-circuits with a ValidationProblemDetails 400 if invalid.
  • Minimal APIs in .NET 10: AddValidation() plus a source generator discovers types with validation attributes and adds an endpoint filter that validates parameters and returns a 400 ProblemDetails. Before .NET 10 you needed an endpoint filter or a library.

4. Filters

MVC filters run inside the action invoker in stages (authorisation → resource → model binding → action → exception → result). Endpoint filters wrap only the handler invocation, with access to the bound arguments via EndpointFilterInvocationContext.Arguments. There is no direct equivalent of resource or result filters in Minimal APIs; middleware or endpoint filters cover most cases.

5. Performance and AOT

Minimal APIs avoid controller activation, the filter pipeline and ModelState. Microsoft's benchmarks show higher throughput, but in real services the database dominates. Native AOT requires the trimming-safe, source-generated path, which MVC (reflection-heavy) doesn't support.

Try it yourself

  1. Implement GET /orders/{id} both ways in one app and compare the OpenAPI output.
  2. Add builder.Services.AddValidation() and a [Range] attribute on a Minimal API record; post invalid data and read the 400.
  3. Benchmark both endpoints with bombardier -c 64 -d 30s and compare RPS.
  4. Publish a Minimal API with PublishAot=true and measure start-up time and image size.

💻 Code

The same endpoint as a Minimal API and as a controller, with .NET 10 validation.

// Program.cs
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddValidation();      // .NET 10: DataAnnotations validation for Minimal APIs
builder.Services.AddControllers();     // only if you also use controllers
builder.Services.AddSingleton<IOrderStore, InMemoryOrderStore>();
var app = builder.Build();

// Minimal API: handler mapped directly; Results<...> documents both outcomes
app.MapPost("/minimal/orders", async Task<Results<Created<Order>, ValidationProblem>> (
    CreateOrder cmd, IOrderStore store, CancellationToken ct) =>
{
    var order = await store.AddAsync(cmd, ct);
    return TypedResults.Created($"/minimal/orders/{order.Id}", order);
});

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

public sealed record CreateOrder([Required] string Sku, [Range(1, 100)] int Quantity);
public sealed record Order(int Id, string Sku, int Quantity);

public interface IOrderStore { Task<Order> AddAsync(CreateOrder cmd, CancellationToken ct); }
public sealed class InMemoryOrderStore : IOrderStore
{
    private int _next;
    public Task<Order> AddAsync(CreateOrder cmd, CancellationToken ct) =>
        Task.FromResult(new Order(Interlocked.Increment(ref _next), cmd.Sku, cmd.Quantity));
}

// Controller: [ApiController] gives automatic 400s and [FromBody] inference
[ApiController]
[Route("controller/orders")]
public sealed class OrdersController(IOrderStore store) : ControllerBase
{
    [HttpPost]
    [ProducesResponseType<Order>(StatusCodes.Status201Created)]
    public async Task<ActionResult<Order>> Create(CreateOrder cmd, CancellationToken ct)
    {
        var order = await store.AddAsync(cmd, ct);
        return Created($"/controller/orders/{order.Id}", order);
    }
}

⚠ Common mistakes

  • Mistake: Believing Minimal APIs are only for demos or tiny services. Why it is wrong: They support groups, filters, auth, OpenAPI, validation (.NET 10) and scale to large APIs with good structure. Instead: Judge them on features you need, not on the name.
  • Mistake: Putting every Minimal API endpoint in Program.cs. Why it is wrong: It becomes unreadable and untestable. Instead: One extension method per feature with MapGroup.
  • Mistake: Assuming Minimal APIs validate DataAnnotations automatically in every version. Why it is wrong: Before .NET 10 they did not; even in .NET 10 you must call AddValidation(). Instead: Register validation explicitly and test invalid input.
  • Mistake: Choosing Minimal APIs for performance alone. Why it is wrong: Framework overhead is microseconds; I/O dominates real latency. Instead: Choose for model, features and AOT needs.
  • Mistake: Expecting MVC filters to apply to Minimal API endpoints. Why it is wrong: MVC filters run only inside the MVC action invoker. Instead: Use endpoint filters or middleware.
  • Mistake: Rewriting a large, healthy controller API as Minimal APIs in one go. Why it is wrong: It is high risk with little user value; behaviour such as binding inference, error shapes and filters differs subtly, and clients notice. Instead: Migrate feature by feature behind contract tests (OpenAPI diff plus integration tests), and only when there is a concrete benefit like Native AOT.
  • Mistake: Mixing both styles randomly in one service. Why it is wrong: Two ways to do validation, errors, filters and auth confuse the team and drift over time, so the same API returns two different 400 shapes. Instead: Pick one per service, or draw a clear boundary and share ProblemDetails and auth policies across both.

🏛 Senior insight: trade-offs

The senior framing is that the choice is a team and consistency decision on top of a shared platform. What actually matters is how endpoints are organised, how validation and errors are standardised (ProblemDetails everywhere), and whether you need AOT or MVC-only features. Migrating an existing healthy controller codebase to Minimal APIs rarely pays back on its own.

Option When it fits Cost When not to
Minimal APIs New APIs, microservices, AOT, small to large teams with conventions Must design your own structure Heavy reliance on MVC filters/formatters
Controllers Existing MVC estates, XML/custom formatters, JSON Patch More ceremony, no AOT Scale-to-zero cold-start sensitive services
Both in one app Gradual migration Two conventions to maintain As a permanent state without boundaries

🔗 Follow-ups the interviewer may ask

  1. When: Candidate says both produce endpoints. Why: Checks that the candidate understands the shared endpoint routing both models use.
    How to answer

    Endpoint routing splits routing into two steps: UseRouting matches the request's path and HTTP method to one endpoint and stores it on HttpContext, and the endpoint middleware at the end executes it. Anything between them, like authorisation, CORS and rate limiting, reads the endpoint's metadata. Routes are defined by templates (/orders/{id:int}, optional and default values, catch-alls {**path}) with constraints that narrow matches. When several routes match, precedence picks the most specific: literals beat parameters, constrained beats unconstrained, catch-alls lose; a true tie throws AmbiguousMatchException. Link generation (LinkGenerator, CreatedAtRoute) builds URLs from route names and values so URLs aren't hard-coded. The trade-off: constraints help disambiguate but are not validation; a failed constraint is a 404, not a 400.

  2. When: Candidate mentions endpoint filters or MVC filters. Why: Checks when cross-cutting logic belongs in middleware rather than filters.
    How to answer

    Middleware is a component in the request pipeline: a RequestDelegate that receives the HttpContext, can do work, calls next to pass the request on, and can do more work when the response comes back. It can also short-circuit by not calling next. Use adds middleware that may call next; Run adds terminal middleware; Map branches the pipeline by path; UseWhen branches on a condition and rejoins, MapWhen branches without rejoining. Because each middleware wraps the next, order is behaviour: exception handling first, then HTTPS, static files, routing, CORS, authentication, authorisation and finally endpoints. Custom middleware can be convention-based (a class with InvokeAsync, created once as a singleton) or implement IMiddleware (resolved from DI per request). The trade-off: convention-based is the fastest default; IMiddleware is clearer when you need scoped dependencies.

↩ Usually asked after

More in ASP.NET Core Fundamentals

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me