Start With Two Lines in Program.cs
For a service with one or two endpoints, map them in Program.cs and stop. The structure below is for when the endpoints multiply, the same checks start repeating, and other teams generate clients from your API.
ASP.NET Core MVC controllers carry a lot of weight: filters, model binding pipelines, action invokers, results executors, view engines you don't use. For an HTTP API that returns JSON, most of that machinery sits idle while still imposing per-request overhead. Minimal APIs, introduced in .NET 6 and matured through .NET 10, strip the model down to its essence: a route, a delegate, a result. The wins are smaller binaries, faster cold starts (especially on Azure Container Apps and AOT), and code that fits on a screen.
Endpoints, Filters, Results
A Minimal API endpoint is three things: a route pattern, a handler delegate (with DI injected through parameters), and a result. The framework handles parameter binding from route, query, header, body, and DI based on type. Cross-cutting behaviour goes into endpoint filters, the lighter-weight equivalent of MVC action filters. Endpoints compose into route groups, which scope authorization, filters, OpenAPI metadata, and prefixes.
flowchart LR R[Request] --> B[Parameter Binding] B --> F1[Endpoint Filter 1] F1 --> F2[Endpoint Filter 2 ...] F2 --> H[Handler Delegate] H --> T[Typed Result<Ok, NotFound, ...>] T --> W[Response Writer] W --> C[Client]
The three doctrines worth internalizing:
- Use typed results.
Results<Ok<T>, NotFound, ValidationProblem>makes every possible response part of the method signature — and OpenAPI picks up every variant automatically. - Group ruthlessly. One
MapGroupper resource (or per version). Auth, filters, rate limits, and tags attach to the group, not to every endpoint. - Use endpoint filters for cross-cutting behaviour. Validation, audit logging, idempotency keys — never repeat them in handler bodies.
A Production-Shaped Service
3.1 Wiring the host
.NET 9 ships built-in OpenAPI support via Microsoft.AspNetCore.OpenApi, replacing Swashbuckle for spec generation. Use Scalar or Swagger UI as a viewer if you want one.
var builder = WebApplication.CreateBuilder(args);
builder.Services
.AddOpenApi() // built in since .NET 9
.AddProblemDetails()
.AddRateLimiter(o => o.AddFixedWindowLimiter("api", w => { w.Window = TimeSpan.FromSeconds(10); w.PermitLimit = 100; }))
.AddAuthorization()
.AddAuthentication().AddJwtBearer();
builder.Services.AddKeyedScoped<IOrderRepository, SqlOrderRepository>("primary");
builder.Services.AddKeyedScoped<IOrderRepository, ReadReplicaOrderRepository>("replica");
var app = builder.Build();
app.UseExceptionHandler();
app.UseRateLimiter();
app.UseAuthentication();
app.UseAuthorization();
app.MapOpenApi(); // serves /openapi/v1.json
app.MapOrders(); // route group below
app.Run();3.2 A route group with filters and typed results
public static class OrdersModule
{
public static IEndpointRouteBuilder MapOrders(this IEndpointRouteBuilder app)
{
var group = app.MapGroup("/api/v1/orders")
.WithTags("Orders")
.RequireAuthorization()
.RequireRateLimiting("api")
.AddEndpointFilter<ValidationFilter>();
group.MapPost("/", PlaceOrder).WithName("PlaceOrder");
group.MapGet("/{id:guid}", GetOrder).WithName("GetOrder");
group.MapDelete("/{id:guid}", CancelOrder)
.WithName("CancelOrder")
.ProducesProblem(StatusCodes.Status409Conflict);
return app;
}
private static async Task<Results<Created<OrderDto>, ValidationProblem>> PlaceOrder(
PlaceOrderRequest body,
[FromKeyedServices("primary")] IOrderRepository repo,
TimeProvider clock,
CancellationToken ct)
{
var order = Order.Place(body.CustomerId, body.Lines, clock);
await repo.AddAsync(order, ct);
var dto = OrderDto.From(order);
return TypedResults.Created($"/api/v1/orders/{dto.Id}", dto);
}
private static async Task<Results<Ok<OrderDto>, NotFound>> GetOrder(
Guid id,
[FromKeyedServices("replica")] IOrderRepository repo,
CancellationToken ct)
{
var order = await repo.FindAsync(new OrderId(id), ct);
return order is null ? TypedResults.NotFound() : TypedResults.Ok(OrderDto.From(order));
}
private static async Task<Results<NoContent, NotFound, ProblemHttpResult>> CancelOrder(
Guid id,
[FromKeyedServices("primary")] IOrderRepository repo,
CancellationToken ct)
{
try
{
var ok = await repo.TryCancelAsync(new OrderId(id), ct);
return ok ? TypedResults.NoContent() : TypedResults.NotFound();
}
catch (DomainException ex)
{
return TypedResults.Problem(ex.Message, statusCode: 409);
}
}
}Every endpoint declares its responses in the return type, and OpenAPI picks up the result types from it. The 409 is different: its status is set at runtime, so OpenAPI can't see it, which is why CancelOrder declares it with ProducesProblem. Generated clients then see 201, 400, 404 and 409 as typed responses.
Check it: Open the generated OpenAPI document and find one endpoint. Every status code it can return should be listed with its type.
3.3 An endpoint filter — validation done once
public sealed class ValidationFilter(IServiceProvider sp) : IEndpointFilter
{
public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext ctx, EndpointFilterDelegate next)
{
foreach (var arg in ctx.Arguments)
{
if (arg is null) continue;
var validatorType = typeof(IValidator<>).MakeGenericType(arg.GetType());
if (sp.GetService(validatorType) is IValidator validator)
{
var result = await validator.ValidateAsync(new ValidationContext<object>(arg));
if (!result.IsValid)
return TypedResults.ValidationProblem(result.ToDictionary());
}
}
return await next(ctx);
}
}Check it: Post an invalid body to every endpoint in the group. Each should return a 400 problem response, with no validation code in the handler.
3.4 Keyed services in handlers (.NET 8+)
[FromKeyedServices("replica")] resolves a specific implementation registered with that key — useful for read replica routing, multi-tenant strategy selection, or feature-flag-driven swaps without an abstract factory.
3.5 Testing with WebApplicationFactory
public sealed class OrdersApiTests(WebApplicationFactory<Program> factory) : IClassFixture<WebApplicationFactory<Program>>
{
[Fact]
public async Task Place_returns_201_with_location()
{
var client = factory.WithWebHostBuilder(b => b.ConfigureServices(s =>
{
s.RemoveAll<DbContextOptions<AppDb>>();
// An in-memory SQLite database only lives as long as its connection, so keep one
// open and create the schema first. Prefer the real engine for query-heavy tests.
var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
s.AddDbContext<AppDb>(o => o.UseSqlite(connection));
})).CreateClient();
var response = await client.PostAsJsonAsync("/api/v1/orders", new PlaceOrderRequest(/* ... */));
response.StatusCode.Should().Be(HttpStatusCode.Created);
response.Headers.Location.Should().NotBeNull();
}
}Pitfalls That Negate the Wins
- Returning
IResultinstead of typed results. OpenAPI loses response metadata and clients fall back toany. Always project toResults<...>. - Putting business logic in the handler delegate. The delegate is a thin edge — bind, dispatch to a handler/use-case, project the result. A 50-line lambda is a refactor signal.
- Re-implementing filters per endpoint. Validation, idempotency, audit logging — extract them into endpoint filters and attach them to the group.
- Swashbuckle on .NET 9 and later. The built-in
AddOpenApipath is the supported route now. Swashbuckle is no longer the default template, and using both fights for control of the spec. - Forgetting the
CancellationToken. Always include it as a handler parameter. Long-running queries that ignore client cancellation hold connections open and starve the thread pool. - Inferring binding source from convention. Bind a primitive from the route, a complex object from the body, an
IFormFilefrom form data — but be explicit with[FromBody],[FromQuery],[FromHeader]when the intent isn't obvious. Saves a class of debugging sessions. - One file per endpoint. Nope. Group endpoints by feature/resource into a static module class with a
Map*extension method. Vertical slices apply here too.
Check it: Find your longest endpoint lambda. If it holds business logic, move that into a use case the endpoint calls.
What .NET 10 Added
Minimal APIs were missing a few things that kept teams on controllers. .NET 10 closed the most important gaps.
Built-in validation is the big one. Call AddValidation(), annotate your request types with data annotations, and invalid requests return a 400 problem response with no filter code of your own. Before this, you needed a third-party package or a hand-written endpoint filter. It uses a source generator, so it works with Native AOT:
builder.Services.AddValidation();
public record CreateOrder([Required] string CustomerId, [Range(1, 100)] int Quantity);
app.MapPost("/orders", (CreateOrder order) => TypedResults.Created($"/orders/{Guid.NewGuid()}", order));
TypedResults.ServerSentEvents gives you streaming responses with very little code, which suits LLM output. OpenAPI generation now produces 3.1 documents by default, so you can drop Swashbuckle for most services.
Organising more than ten endpoints
The main objection to minimal APIs is that Program.cs becomes a mess. It doesn't have to. Group routes with MapGroup, and keep each feature in its own static class with one Map extension method. Apply authorisation, rate limiting and filters at the group level, so a new endpoint inherits them, and can't forget them:
var orders = app.MapGroup("/orders")
.RequireAuthorization()
.RequireRateLimiting("per-user")
.WithTags("Orders");
orders.MapGet("/{id:guid}", GetOrder);
orders.MapPost("/", CreateOrder);
Use TypedResults rather than Results too. The return type then appears in the signature, which improves the OpenAPI output and makes handlers easy to unit test.
Check it: Add an endpoint to an existing group and call it without a token. It should be refused, with nothing added by you.
When controllers still make sense
If you have a large existing controller codebase, there's no reason to migrate for its own sake. Both are supported and can sit in one app. New services are a different question. I'd start with minimal APIs, and I've yet to need to go back.
Testing Endpoints
WebApplicationFactory works with minimal APIs just as it does with controllers, so test through HTTP, and cover status codes and validation. For handlers written as static methods, a direct unit test is simple too, since TypedResults return values can be asserted on by type.
Try It on Your Own System This Week
Three checks on an API you already run, about an hour in total:
- Look for handlers with no CancellationToken parameter. A query that ignores cancellation holds its connection open.
- Check whether two OpenAPI generators are installed. Two of them fight for control of the spec.
- If you plan to use Native AOT, publish with it now. Reflection-heavy filters are the usual stumbling block.
What I Would Do on a New API
- Default to Minimal APIs for new HTTP services. Reach for Controllers when you need MVC features (Razor views, sophisticated model binding conventions, legacy filters).
- Use
MapGroupliberally. Authorisation, rate limiting, and OpenAPI tags attach to the group, not to every endpoint. - Return typed results. Make every status code part of the contract.
- Cross-cutting behaviour goes in endpoint filters. Don't repeat it across handlers.
- Use
[FromKeyedServices]for replica/strategy/multi-tenant resolution without abstract factories. - Use the native
AddOpenApi(built in since .NET 9); pick a viewer (Scalar, Swagger UI) only if you need one. - Test with
WebApplicationFactory<Program>— the same approach you used for Controllers works unchanged. - Test for AOT compatibility early if you're targeting Azure Container Apps with Native AOT. Reflection-heavy filters (some validation libraries) are the usual stumbling block.