Minimal APIs (.NET 10)
Core Principles
- Minimal APIs are the default. Use controllers only when migrating legacy code. Minimal APIs are lighter, faster, and compose well with any architecture style.
- One
IEndpointper feature, discovered by convention. Each feature folder has one endpoint class.Program.cscalls one discovery method (app.MapModules()in a modular app,app.MapEndpoints()in a single project) and never changes when features are added. - Return
TypedResultsunions.Results<Created<T>, ProblemHttpResult>gives compile-time checking and correct OpenAPI documentation without.Produces()calls.Results.Ok(value)andIResultgive neither. - Metadata over comments.
.WithName(),.WithSummary()and XML comments on request/response records feed the OpenAPI document.
Patterns
One IEndpoint per Feature (Required Pattern)
The endpoint is a thin adapter: route, authorization, OpenAPI text, and a call to the feature's handler. The full interfaces (IEndpoint, IHandler, IModule) and discovery code are in skills/modular-slices/references/building-blocks.md.
public interface IEndpoint
{
void Map(IEndpointRouteBuilder endpoints);
}
// Features/PlaceOrder/PlaceOrderEndpoint.cs
internal sealed class PlaceOrderEndpoint : IEndpoint
{
public void Map(IEndpointRouteBuilder endpoints) =>
endpoints.MapPost("/", HandleAsync)
.RequirePermission(OrdersPermissions.Manage)
.WithName("PlaceOrder")
.WithSummary("Places an order");
private static Task<Results<Created<OrderResponse>, ProblemHttpResult>> HandleAsync(
PlaceOrderRequest request, PlaceOrderHandler handler, CancellationToken ct) =>
handler.HandleAsync(request, ct);
}
In a modular app, MapModules() maps every module's endpoints under /api/v1/{module}, tags them with the module name, and adds the validation filter, so the route above is relative to the module group:
// Program.cs (modular): never changes when features are added
builder.AddModule<CatalogModule>();
builder.AddModule<OrdersModule>();
var app = builder.Build();
app.MapModules();
In a single-project app, one scan does the same job:
public static IEndpointRouteBuilder MapEndpoints(this IEndpointRouteBuilder app)
{
var api = app.MapGroup("/api")
.AddEndpointFilterFactory(RequestValidation.Create)
.ProducesValidationProblem();
foreach (var type in typeof(Program).Assembly.GetTypes()
.Where(t => t is { IsClass: true, IsAbstract: false } && typeof(IEndpoint).IsAssignableFrom(t))
.OrderBy(t => t.FullName, StringComparer.Ordinal))
((IEndpoint)Activator.CreateInstance(type)!).Map(api);
return app;
}
Endpoints are sorted by name so routes and the OpenAPI document come out in the same order on every build.
TypedResults Unions for Type-Safe Responses
The handler's return type is the endpoint's HTTP contract. Errors are ProblemDetails with a stable code built by the Problems helper (see the error-handling skill).
internal sealed class GetOrderHandler(OrdersDbContext db) : IHandler
{
public async Task<Results<Ok<OrderResponse>, ProblemHttpResult>> HandleAsync(Guid id, CancellationToken ct)
{
var order = await db.Orders.AsNoTracking()
.Where(o => o.Id == id)
.Select(o => new OrderResponse(o.Id, o.ProductId, o.Quantity, o.Total, o.PlacedAt))
.FirstOrDefaultAsync(ct);
return order is null ? Problems.NotFound() : TypedResults.Ok(order);
}
}
Returning a result type that is not in the union is a compile error, and OpenAPI documents 200 and the problem response automatically.
Parameter Binding
.NET 10 minimal APIs bind parameters from route, query, header, body, and DI automatically.
// Route parameters
endpoints.MapGet("/{id:guid}", (Guid id, GetOrderHandler handler, CancellationToken ct) => handler.HandleAsync(id, ct));
// Query parameters (nullable = optional)
endpoints.MapGet("/", (int page, int? pageSize, string? status) => ...);
// Complex query parameters with [AsParameters]
public sealed record ListOrdersQuery(int Page = 1, int PageSize = 20, string? Status = null);
endpoints.MapGet("/", ([AsParameters] ListOrdersQuery query, ListOrdersHandler handler, CancellationToken ct) => ...);
// Header binding (FromHeader needs using Microsoft.AspNetCore.Mvc;)
endpoints.MapGet("/", ([FromHeader(Name = "X-Correlation-Id")] string? correlationId) => ...);
// DI services (including handlers) are resolved without an attribute
endpoints.MapPost("/", (PlaceOrderRequest request, PlaceOrderHandler handler, CancellationToken ct) => ...);
Endpoint Filters
Filters are the minimal API equivalent of action filters. Use them for cross-cutting concerns like validation, logging, and idempotency checks.
Validation uses one filter factory on the top-level group (RequestValidation.Create, in the modular-slices building blocks). It runs the FluentValidation validator of any parameter that has one and returns a 400 ValidationProblem with code: validation-failed. Endpoints never add validation filters one by one, and endpoints without validated parameters get no filter at all.
// Once, on the top-level group (MapModules and MapEndpoints already do this)
var api = app.MapGroup("/api/v1")
.AddEndpointFilterFactory(RequestValidation.Create)
.ProducesValidationProblem();
// Other filters on a single endpoint
endpoints.MapPost("/", HandleAsync).AddEndpointFilter<IdempotencyFilter>();
OpenAPI Configuration
.NET 10 has built-in OpenAPI support. Use it instead of Swashbuckle (see the openapi skill).
builder.Services.AddOpenApi();
var app = builder.Build();
if (app.Environment.IsDevelopment())
app.MapOpenApi();
app.MapModules(); // or app.MapEndpoints() in a single project
// Inside an IEndpoint: the union supplies the response types; add names and text
endpoints.MapPost("/", HandleAsync)
.WithName("PlaceOrder")
.WithSummary("Places an order")
.WithDescription("Places an order for one product. Fails with orders.product-not-found if the product is unknown.");
Rate Limiting
Per-caller partitions, a strict policy on auth endpoints, 429 with Retry-After and multi-instance behaviour are in the rate-limiting skill. On an endpoint it is one call: .RequireRateLimiting("auth").
Output Caching
builder.Services.AddOutputCache(options =>
{
options.AddBasePolicy(policy => policy.Expire(TimeSpan.FromMinutes(5)));
options.AddPolicy("ByIdCache", policy => policy
.Expire(TimeSpan.FromMinutes(10))
.SetVaryByRouteValue("id"));
});
endpoints.MapGet("/{id:guid}", HandleAsync).CacheOutput("ByIdCache");
API Versioning
Version from day one: URL segment (/api/v1/...) is the default, a breaking change means a new version, and features opt into versions with .MapToApiVersion(2, 0). Setup, version sets with IEndpoint, deprecation and anti-patterns are in references/api-versioning.md.
Anti-patterns
Don't Put Endpoints in Program.cs
// BAD: endpoints scattered in Program.cs
app.MapGet("/orders", async (AppDbContext db) => await db.Orders.ToListAsync());
app.MapPost("/orders", async (Order order, AppDbContext db) => { /* ... */ });
// ALSO BAD: manual wiring that grows with every feature
app.MapGroup("/api/orders").WithTags("Orders").MapOrderEndpoints();
app.MapGroup("/api/products").WithTags("Products").MapProductEndpoints();
// GOOD: auto-discovered, Program.cs never changes
app.MapModules(); // every IEndpoint in every module
Don't Put a Whole Resource in One Endpoint Class
// BAD: every order operation edits this file
public sealed class OrderEndpoints : IEndpointGroup
{
public void Map(IEndpointRouteBuilder app) { /* MapPost, MapGet, MapPut, MapDelete, cancel... */ }
}
// GOOD: one IEndpoint per feature folder
internal sealed class CancelOrderEndpoint : IEndpoint
{
public void Map(IEndpointRouteBuilder endpoints) =>
endpoints.MapPost("/{id:guid}/cancel", HandleAsync).RequirePermission(OrdersPermissions.Manage);
private static Task<Results<Ok<OrderResponse>, ProblemHttpResult>> HandleAsync(
Guid id, CancelOrderRequest request, CancelOrderHandler handler, CancellationToken ct) =>
handler.HandleAsync(id, request, ct);
}
Don't Use Untyped Results
// BAD: IResult hides the status codes from the compiler and from OpenAPI
private static async Task<IResult> GetOrder(Guid id, OrdersDbContext db)
{
var order = await db.Orders.FindAsync(id);
return order is not null ? Results.Ok(order) : Results.NotFound();
}
// GOOD: TypedResults union, ProblemDetails for the failure
private static async Task<Results<Ok<OrderResponse>, ProblemHttpResult>> GetOrder(
Guid id, OrdersDbContext db, CancellationToken ct)
{
var order = await db.Orders.AsNoTracking()
.Where(o => o.Id == id)
.Select(o => new OrderResponse(o.Id, o.ProductId, o.Quantity, o.Total, o.PlacedAt))
.FirstOrDefaultAsync(ct);
return order is not null ? TypedResults.Ok(order) : Problems.NotFound();
}
Don't Return Domain Entities Directly
// BAD: leaks internal structure, can't evolve independently
return TypedResults.Ok(await db.Orders.Include(o => o.Items).FirstOrDefaultAsync(o => o.Id == id, ct));
// GOOD: project to a response record
var order = await db.Orders
.Where(o => o.Id == id)
.Select(o => new OrderResponse(o.Id, o.ProductId, o.Quantity, o.Total, o.PlacedAt))
.FirstOrDefaultAsync(ct);
Decision Guide
| Scenario | Recommendation |
|---|---|
| New HTTP API with several business areas | IEndpoint per feature inside modules + app.MapModules() (modular-slices) |
| Small single-area API | IEndpoint per feature + app.MapEndpoints() (architecture-advisor, references/vertical-slice.md) |
| Return type | TypedResults union, errors as ProblemHttpResult with a stable code |
| Existing MVC project | Keep controllers, migrate incrementally |
Existing IEndpointGroup codebase |
Keep it; do not mix both styles in one project |
| OpenAPI documentation | TypedResults unions + .WithName() + .WithSummary() |
| Request validation | One FluentValidation filter factory on the top-level group |
| Authentication/authorization | .RequirePermission(...) or .RequireAuthorization(...) on every endpoint, plus a fallback policy |
| Rate limiting | rate-limiting skill: per-caller policy + .RequireRateLimiting() |
| Response caching | AddOutputCache + .CacheOutput() |
| Evolving the API with breaking changes | New API version; see references/api-versioning.md |
| Complex model binding | [AsParameters] with a record type |
