skip to content

Minimal APIs

Writing HTTP endpoints as route handlers with MapGet and friends: parameter inference, TypedResults, route groups with endpoint filters and built-in validation. The default style for new APIs.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

18

In ASP.NET Core Minimal APIs, what does app.MapGroup("/api/v1/fleet") return, and how does it apply conventions once to many endpoints?

level: juniorimportance: must knowfreq 60%

answer

  1. one object, two roles
  2. prefix joined to each route pattern
  3. IEndpointRouteBuilder plus IEndpointConventionBuilder
  4. WithTags and AddEndpointFilter on the group
  5. not a middleware branch like app.Map

basics

~20 s

It returns a RouteGroupBuilder, both a route builder and a convention builder: endpoints mapped on it get the group prefix in front of their pattern, and WithTags or AddEndpointFilter on it reach every endpoint inside, nested groups included.

solid answer

~40 s

`MapGroup(prefix)` returns a `RouteGroupBuilder`, a sealed class that implements both `IEndpointRouteBuilder` and `IEndpointConventionBuilder`. Because it is a route builder, you call `MapGet`, `MapPost` or another `MapGroup` on it, and the group's prefix (route parameters and constraints included) is combined with each endpoint's own pattern. Because it is a convention builder, `WithTags("Fleet")`, `WithMetadata(...)` or `AddEndpointFilter<TimingFilter>()` on the group behave as if you had called them on every endpoint inside it, nested groups too, and they are applied before the endpoint's own conventions. The group only stores those conventions; they run when the endpoints are built, so they also reach endpoints mapped before the call. A group is not a middleware branch: there is no separate pipeline and `Request.PathBase` is untouched.

code

csharp · 15 lines
csharp
var fleet = app.MapGroup("/api/v1/fleet")
    .WithTags("Fleet")
    .AddEndpointFilter<TimingFilter>();

fleet.MapGet("/trucks", (IFleetStore store) => store.ListTrucksAsync());

var truck = fleet.MapGroup("/trucks/{truckId:int}");

// GET /api/v1/fleet/trucks/42/position
truck.MapGet("/position", (int truckId, IFleetStore store) =>
    store.GetPositionAsync(truckId));

// POST /api/v1/fleet/trucks/42/pings
truck.MapPost("/pings", (int truckId, Ping ping, IFleetStore store) =>
    store.AddPingAsync(truckId, ping));

go deeper

for a junior

Recall that MapGroup returns a RouteGroupBuilder, that its prefix is joined to each endpoint's pattern, and that WithTags or AddEndpointFilter on it reach every endpoint inside.

for a middle

Explain the two interfaces, how nested prefixes and route parameters combine, and why a convention called after MapGet still applies: conventions are stored and run when endpoints are built.

for a senior

Use groups to keep policy auditable: one group per API version or resource for shared filters and metadata, nested groups for sub-resources, and endpoint-level calls only to refine what the group set.

for a principal

Weigh convenience against visibility: deep nesting hides what an endpoint really carries, so agree where the team reads an endpoint's effective filters and metadata before groups multiply.

## What `MapGroup` returns `app.MapGroup("/api/v1/fleet")` is an extension method on `IEndpointRouteBuilder` (a `WebApplication` is one) and returns a **`RouteGroupBuilder`**. That sealed class implements two interfaces at once: - **`IEndpointRouteBuilder`**: you can call `MapGet`, `MapPost`, `MapPut`, `MapDelete` and `MapGroup` on it. Endpoints mapped there live in the group's own data source, which the outer builder picks up. - **`IEndpointConventionBuilder`**: every convention extension (`WithTags`, `WithMetadata`, `AddEndpointFilter`, `AddEndpointFilterFactory` and the rest) can be chained on the group, exactly as on the `RouteHandlerBuilder` that a single `MapGet` returns. A route group is therefore a **prefix plus a list of conventions** applied to every endpoint it contains. The `webapiaot` template's sample is written this way: `var todosApi = app.MapGroup("/todos");` followed by `todosApi.MapGet(...)`. ## Prefixes, nesting and route parameters In a truck-fleet tracker: ```csharp var fleet = app.MapGroup("/api/v1/fleet") .WithTags("Fleet") .AddEndpointFilter<TimingFilter>(); fleet.MapGet("/trucks", (IFleetStore store) => store.ListTrucksAsync()); var truck = fleet.MapGroup("/trucks/{truckId:int}"); truck.MapGet("/position", (int truckId, IFleetStore store) => store.GetPositionAsync(truckId)); ``` - The prefixes are **combined into one route pattern** per endpoint: the position endpoint matches `GET /api/v1/fleet/trucks/{truckId:int}/position`. - A **route parameter declared in a prefix** (`{truckId:int}`) is an ordinary route value, so handlers in the group and in its nested groups bind it like a parameter of their own template, and the `:int` constraint takes part in matching. - The prefix may be an **empty string**: `app.MapGroup("")` puts conventions on a set of endpoints without changing their URLs. - Nesting works because a group is itself an `IEndpointRouteBuilder`; a nested group inherits the outer prefix and the outer conventions. ## Conventions set once Calling a convention on a group has the same effect as calling it on every endpoint in it, ahead of anything an inner group or the endpoint adds. | Call on the group | Effect on each endpoint | |---|---| | `WithTags("Fleet")` | adds a `TagsAttribute` (`ITagsMetadata`), which OpenAPI uses to group operations | | `WithMetadata(obj)` | appends any metadata object that middleware and filters can read from the endpoint | | `AddEndpointFilter<TimingFilter>()` | wraps the handler in that filter | | `AddEndpointFilterFactory(...)` | runs a filter factory once per endpoint when it is built | Authorization, CORS and OpenAPI response metadata are applied to groups through the same mechanism; each has its own topic. ## When the conventions are applied The group only **stores** its conventions; calling `WithTags` touches no endpoint. When the endpoint data sources are first read (at the latest when routing handles the first request), each endpoint is built and receives, in this order: 1. the outermost group's conventions, 2. then each inner group's conventions, outside in, 3. then the endpoint's own conventions. Two consequences follow. A convention called on the group **after** `fleet.MapGet(...)` still reaches that endpoint, because nothing was applied at mapping time. And because the group's metadata lands earlier in the endpoint's metadata list, `EndpointMetadataCollection.GetMetadata<T>()` (which returns the most significant, last item) prefers what the endpoint itself set: an endpoint refines its group, never the other way round. ## What a group is not - **Not a middleware branch.** `app.Map("/api/v1/fleet", branch => ...)` forks the middleware pipeline and, by default, moves the matched segment into `Request.PathBase`. `MapGroup` forks nothing; its endpoints join the app's single routing table and run through the same middleware as every other endpoint. - **Not a path-base change.** `Request.PathBase` and `Request.Path` are untouched; the prefix is simply part of each endpoint's route pattern. - **Not consulted per request.** Request handling never asks the group anything; it sees only endpoints whose metadata and filters were copied from the group when they were built. ## What interviewers listen for - The return type and its two interfaces, not only "it adds a prefix". - That nested groups inherit prefixes and conventions, and that route parameters in a prefix bind in handlers. - That conventions are applied at build time, outer group first, so an endpoint can refine what its group set.

  • Can a handler in a nested group bind a route parameter that appears only in a group prefix?
    Yes. The prefixes are combined into one route pattern, so `{truckId:int}` declared in `fleet.MapGroup("/trucks/{truckId:int}")` is a route value for every endpoint below it. A handler parameter named `truckId` binds it as if it were in the endpoint's own template, and the `:int` constraint applies during matching.
  • Why would you call app.MapGroup with an empty string?
    To apply conventions to a set of endpoints without changing their URLs. `var ops = app.MapGroup("").AddEndpointFilter<AuditFilter>();` lets you map `ops.MapPost("/fleet/recalls", ...)` and `ops.MapPost("/fleet/retire", ...)` at their own paths while both carry the audit filter.
  • If WithTags is called on the group after the endpoints are mapped, do those endpoints get the tag?
    Yes. `RouteGroupBuilder` only records conventions in a list, and the list is applied when the group's endpoints are built, which happens when routing first reads the endpoint data sources. Mapping order and convention order therefore do not matter within startup code.

  • MapGroup returns a RouteHandlerBuilder, the same type MapGet returns.
  • MapGroup forks the middleware pipeline like app.Map and moves the prefix into PathBase.
  • Group conventions reach only the endpoints mapped after the convention call.
  • Handlers cannot bind route parameters declared in a group prefix.
  • A nested group starts clean and does not inherit the outer group's filters or tags.
open as a page

In an ASP.NET Core Minimal API, how does a MapGet or MapPost handler decide where each of its parameters is bound from?

level: juniorimportance: must knowfreq 72%

basics

~20 s

Minimal APIs infer each parameter's source: a simple type binds from the route if its name is a route parameter, else from the query; registered services come from DI; an unregistered complex type on MapPost is the JSON body.

open as a page

In an ASP.NET Core Minimal API, what response does a handler produce when it returns a string, a plain object, or an IResult like TypedResults.Ok?

level: juniorimportance: must knowfreq 66%

basics

~10 s

A string is written as 200 text/plain, any other object is serialized to 200 application/json, and an IResult writes its own status, headers and body through ExecuteAsync; void or Task gives an empty 200.

open as a page

In ASP.NET Core 10 Minimal APIs, what does builder.Services.AddValidation() do, and what happened to DataAnnotations on handler parameters before it?

level: juniorimportance: must knowfreq 55%

basics

~20 s

AddValidation switches on built-in validation in .NET 10: a framework endpoint filter checks DataAnnotations and IValidatableObject on bound parameters and body types, nested members included, and answers 400 before the handler runs. Earlier Minimal APIs ignored those attributes.

open as a page

In an ASP.NET Core Minimal API, how do you write an IEndpointFilter that reads a handler argument and stops the request before the handler runs?

level: middleimportance: must knowfreq 55%

basics

~10 s

Implement IEndpointFilter.InvokeAsync(EndpointFilterInvocationContext, EndpointFilterDelegate), read the bound value with context.GetArgument<T>(index), and return a result such as TypedResults.NotFound() without calling next to stop; otherwise return await next(context).

open as a page

In ASP.NET Core Minimal APIs, what is the difference between Results.Ok and TypedResults.Ok, and why is TypedResults usually the better choice?

level: middleimportance: must knowfreq 62%

basics

~20 s

Both write the same 200 JSON response; Results.Ok is declared to return IResult while TypedResults.Ok returns Ok<T>, whose static metadata documents the response, makes tests cast-free and, in ASP.NET Core 10, stops cookie authentication redirecting.

open as a page

In ASP.NET Core Minimal APIs, in what order do endpoint filters on an outer group, an inner group and the endpoint itself run?

level: middleimportance: should knowfreq 45%

basics

~20 s

Outer group filters run first, then inner group filters, then the endpoint's own, whatever order the AddEndpointFilter calls appear in across those builders. On one builder, code before next runs in registration order and code after next in reverse.

open as a page

In ASP.NET Core Minimal APIs, what does [AsParameters] do to a handler parameter, and which shapes of type can it not bind?

level: middleimportance: should knowfreq 40%

basics

~10 s

[AsParameters] treats a class, struct or record as a list of handler parameters: each constructor parameter or settable property is inferred like a handler parameter. It cannot be nested, nullable or abstract.

open as a page

In ASP.NET Core Minimal APIs, why does a MapGet handler with an unregistered RecipeFilter class parameter fail, and in what order is a parameter's source inferred?

level: middleimportance: should knowfreq 45%

basics

~20 s

An unregistered class that has no BindAsync or TryParse is inferred as the JSON body, and GET, DELETE, HEAD, OPTIONS, TRACE and CONNECT endpoints do not allow an inferred body, so building the endpoint throws InvalidOperationException.

open as a page

How does a Results<Ok<ReturnLabel>, NotFound, Conflict<string>> return type work in an ASP.NET Core Minimal API handler, and what are its limits?

level: middleimportance: should knowfreq 48%

basics

~20 s

Results<T1, ..., T6> is a sealed union of two to six IResult types: each listed type converts to it implicitly, it executes whichever result was returned, and it merges every member's metadata, so 200, 404 and 409 are all documented.

open as a page

In ASP.NET Core 10 with AddValidation, how are nested objects and collection items in a Minimal API request body validated, and how are failures keyed?

level: middleimportance: should knowfreq 40%

basics

~20 s

The filter walks the body's object graph using generated metadata, validating each nested object and each non-null collection item, and reports every failure in one 400 keyed by its path, such as Passengers[1].FullName; graphs deeper than MaxDepth (32) throw.

open as a page

In ASP.NET Core Minimal APIs, when would you use AddEndpointFilterFactory instead of AddEndpointFilter, and what runs once versus per request?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Use a filter factory when a group-wide filter must adapt to each handler: the factory runs once per endpoint at build time with the handler's MethodInfo, and returns either a per-request EndpointFilterDelegate or next unchanged to skip that endpoint.

open as a page

A Minimal API recipe search in ASP.NET Core 10 returns empty 400 responses in production and logs nothing; what does the binder do on failure, and how does ThrowOnBadRequest help?

level: seniorimportance: should knowfreq 38%

basics

~20 s

On a binding failure the Minimal API binder sets 400 (415 for a wrong content type), skips the handler and logs only at Debug. RouteHandlerOptions.ThrowOnBadRequest, true only in Development, throws BadHttpRequestException with the reason instead.

open as a page

In ASP.NET Core Minimal APIs, when do you give a custom type a static TryParse, and when a BindAsync or IBindableFromHttpContext<T> instead?

level: seniorimportance: should knowfreq 35%

basics

~10 s

Use TryParse when the value is one string from the route, query or a header; use BindAsync or IBindableFromHttpContext<T> when binding needs the whole HttpContext, such as several query keys, headers or async work.

open as a page

In ASP.NET Core Minimal APIs, how do you write a custom IResult that also describes its own response through IEndpointMetadataProvider?

level: seniorimportance: should knowfreq 28%

basics

~10 s

Implement IResult.ExecuteAsync to write the status, headers and body, and IEndpointMetadataProvider's static PopulateMetadata to add a ProducesResponseTypeMetadata; the metadata is used only when the handler's declared return type is your type.

open as a page

In ASP.NET Core 10, how do you exempt a Minimal API endpoint from AddValidation, and where does the built-in validation filter run relative to your own endpoint filters?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Call .DisableValidation() on the endpoint or its group, or mark one parameter, property or type [SkipValidation]. The built-in filter is inserted ahead of all your filters, so a failed check returns 400 before any of them runs.

open as a page

In ASP.NET Core 10, Program.cs calls AddValidation, yet a reservation body's property rules never fire for endpoints mapped in a separate class library. Why, and how do you fix it?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Type metadata comes from a source generator that scans only the assembly calling AddValidation; the library's endpoints were never seen, so their body types are skipped silently. Call AddValidation from the library too, and keep validated types public.

open as a page

In an ASP.NET Core Minimal API, what does a timing endpoint filter on the /api/v1/fleet group measure, and can it still set a response header after next returns?

level: seniorimportance: nice to knowfreq 20%

basics

~20 s

It times the inner filters and the handler with its awaited work, not routing, binding or serialization; the result is written after the filter chain returns, so a header set after next is still sent unless the handler wrote the response itself.

open as a page