الانتقال إلى المحتوى
.NETMinimal APIs· 8 دقائق للقراءة

Minimal APIs in Production: What They Can Do That People Assume They Can't

Route groups, endpoint filters, typed results and built-in validation in .NET 10, and the short list of things controllers still do better.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • .NET 10
محتويات المقال

A team starts a new orders service. In the design review, someone says: "Minimal APIs are fine for the prototype, but we'll switch to controllers before it goes live, or 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

The belief: minimal APIs are for demos, tutorials and three-endpoint microservices. A real application needs controllers, because only controllers give you structure, filters, validation, API documentation and testable code.

It isn't a silly belief. The name says "minimal", and the first example everyone sees is 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.

Today the same docs say the opposite of the myth: for new projects, Microsoft recommends minimal APIs, and controllers are the alternative for specific needs.

What actually happens

Same app, a different way to declare endpoints

A minimal API isn't a lighter framework running next to ASP.NET Core. 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

A route handler can be a lambda or an ordinary method, and it doesn't have to live in 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

An runs code before and after a handler, can read and change its arguments, and can return a response without calling the handler at all. A filter added to a group runs for every endpoint in it. That's the job action filters do in MVC, and a filter class that implements IEndpointFilter can take services from dependency injection.

Validation and response types are built in

.NET 10 adds 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

Here are two endpoints from the hook, first as the myth predicts, then with a group. Order is a record with [Required] string Sku and [Range(1, 100)] int Quantity.

C# Program.cs
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();

The handlers move to a file of their own:

C# OrderEndpoints.cs
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);    }}

POST an order with "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

MythReality
Everything lives in Program.csHandlers can be static methods in any file; a group plus an extension method gives one file per feature
There are no filtersEndpoint filters run before and after the handler, can short-circuit, and apply to whole groups
You validate by handAddValidation() in .NET 10 checks DataAnnotations and returns 400 before the handler runs
There's no API documentationTypedResults and Results<...> give OpenAPI the response types automatically
Handlers are hard to unit testHandlers are plain methods, and result types like Ok<Order> are public, so tests can assert on them

What controllers still do better

The docs name four reasons to choose controllers: model binding extensibility (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

  1. Check the controller-only listIf you need one of the four features above, make that part a controller. Otherwise minimal APIs fit, whatever the project size.
  2. Give each feature its own fileWrite a static class with a MapOrders(this RouteGroupBuilder group) style method per feature. Program.cs then reads like a table of contents: one MapGroup line per feature.
  3. Put shared rules on the groupAdd authorization, filters and OpenAPI tags to the group once instead of to every endpoint, so a new endpoint can't forget them.
  4. Turn on validation and typed resultsCall AddValidation() and AddProblemDetails(), return TypedResults with a Results<...> 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() and TypedResults provide 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.

📚 المصادر

  1. APIs overview: Minimal APIs or controllers — Microsoft Learn
  2. Route handlers in Minimal API apps — Microsoft Learn
  3. Minimal APIs quick reference — Microsoft Learn
  4. Create responses in Minimal API applications — Microsoft Learn
  5. Validation in ASP.NET Core — Microsoft Learn

التعليقات (0)