
Minimal APIs in Production: What They Can Do That People Assume They Can't
- كاتب موثّق
- .NET 10
محتويات المقال
Program.cs will become a file nobody wants to open." The prototype ships, the switch never happens, and a year later the prediction has come true: Program.cs is one long list of app.MapGet lambdas, each repeating /api/orders, .RequireAuthorization() and its own hand-written checks. Minimal APIs didn't cause that. Nobody used the parts of them that keep an app organized.
The common misconception
app.MapGet("/", () => "Hello World!") in a single file. It also used to be partly true. Minimal APIs shipped in .NET 6 without endpoint filters, route groups or typed results; those arrived in .NET 7. Microsoft's .NET 6 guidance listed form binding among the reasons to pick controllers, and built-in validation only came with .NET 10.
What actually happens
Same app, a different way to declare endpoints
MapGet and MapPost create endpoints in the same routing system controllers use, and the pipeline, dependency injection, logging, authentication and authorization are all shared, so an authorization policy or the exception handler behaves the same for both. What changes is how you declare an endpoint: a handler with typed parameters instead of an action method on a class.
Structure comes from groups, not from classes
Program.cs. MapGroup creates a : endpoints that share a URL prefix, where anything you add to the group, such as RequireAuthorization() or a filter, applies to every endpoint in it. Groups can nest, and an empty prefix, MapGroup(""), applies metadata or filters without changing any route. The usual layout is one static class per feature with an extension method like MapOrders, so Program.cs only wires features together.
Filters exist too
IEndpointFilter can take services from dependency injection.
Validation and response types are built in
builder.Services.AddValidation(). Before the handler runs, it checks DataAnnotations attributes such as [Required] and [Range] on query, header and body parameters, including nested objects, and answers 400 with the errors when a rule fails. For responses, TypedResults returns concrete types like Ok<Order> and NotFound. Declare a handler as returning Results<Ok<Order>, NotFound> and three things follow: the compiler rejects any other result, OpenAPI reads the possible responses from the signature without extra Produces calls, and a unit test can assert on the returned type.
The orders API, organized
Order is a record with [Required] string Sku and [Range(1, 100)] int Quantity.
var builder = WebApplication.CreateBuilder(args);builder.Services.AddAuthentication().AddJwtBearer();builder.Services.AddAuthorization();builder.Services.AddSingleton<OrderStore>();var app = builder.Build();app.MapGet("/api/orders/{id:int}", (int id, OrderStore store) => store.Find(id) is { } order ? Results.Ok(order) : Results.NotFound()) .RequireAuthorization();app.MapPost("/api/orders", (Order order, OrderStore store) =>{ if (order.Quantity is < 1 or > 100) return Results.BadRequest("Quantity must be between 1 and 100"); store.Add(order); return Results.Created($"/api/orders/{order.Id}", order);}).RequireAuthorization();// ...30 more endpoints, each repeating the prefix, policy and checksapp.Run();var builder = WebApplication.CreateBuilder(args);builder.Services.AddAuthentication().AddJwtBearer();builder.Services.AddAuthorization();builder.Services.AddValidation(); // .NET 10: checks [Range] etc. firstbuilder.Services.AddSingleton<OrderStore>();var app = builder.Build();// one prefix and one policy for every order endpointapp.MapGroup("/api/orders").RequireAuthorization().MapOrders();app.Run();using Microsoft.AspNetCore.Http.HttpResults;public static class OrderEndpoints{ public static RouteGroupBuilder MapOrders(this RouteGroupBuilder group) { group.MapGet("/{id:int}", GetOrder); group.MapPost("/", CreateOrder); return group; } // all possible responses: checked by the compiler, read by OpenAPI static Results<Ok<Order>, NotFound> GetOrder(int id, OrderStore store) => store.Find(id) is { } order ? TypedResults.Ok(order) : TypedResults.NotFound(); static Created<Order> CreateOrder(Order order, OrderStore store) { store.Add(order); return TypedResults.Created($"/api/orders/{order.Id}", order); }}"quantity": 0 to the first version and it answers 400 with a bare string, an error shape no other endpoint shares. The second version never reaches CreateOrder: validation answers 400 with "The field Quantity must be between 1 and 100." under errors.Quantity. Add builder.Services.AddProblemDetails() and that body becomes a standard application/problem+json document with status and traceId, the same shape your other errors can use.
Myth vs reality
Program.cs | |
AddValidation() in .NET 10 checks DataAnnotations and returns 400 before the handler runs | |
TypedResults and Results<...> give OpenAPI the response types automatically | |
Ok<Order> are public, so tests can assert on them |
What controllers still do better
IModelBinderProvider, IModelBinder), advanced validation (IModelValidator), application parts or the application model, and OData. Most of these can be rebuilt by hand in minimal APIs, but controllers ship them. The docs also say controllers may suit large applications with complex business logic and teams fluent in MVC. That's a matter of fit and habit, not of a capability minimal APIs lack.
How to apply it in your project
Check the controller-only list If you need one of the four features above, make that part a controller. Otherwise minimal APIs fit, whatever the project size. Give each feature its own file Write a static class with a MapOrders(this RouteGroupBuilder group)style method per feature.Program.csthen reads like a table of contents: oneMapGroupline per feature.Put shared rules on the group Add authorization, filters and OpenAPI tags to the group once instead of to every endpoint, so a new endpoint can't forget them. Turn on validation and typed results Call AddValidation()andAddProblemDetails(), returnTypedResultswith aResults<...>signature, and send an invalid request to check that it's rejected before the handler.
Key takeaways
Minimal APIs are Microsoft's recommended default for new APIs, and they share routing, middleware, dependency injection and authorization with controllers. Route groups and handler classes give a large API its structure; endpoint filters give it cross-cutting behavior. .NET 10's AddValidation()andTypedResultsprovide validation, consistent errors and OpenAPI metadata, but only once you wire them.Choose controllers for a specific MVC feature, such as a custom model binder or OData, not because an app is big.
التعليقات (0)