Skip to content

8.9 โ€” Route Groups (MapGroup)

โ† Roadmap ยท Section: 8. Routing Prev: 8.8 Areas ยท Next: 8.10 Catch-all routes and slugs

Markers: โญ ๐Ÿ’ป ยท Confidence: ๐Ÿ”ด ยท Last reviewed: โ€”


TL;DR

MapGroup (.NET 7+) collects related minimal API endpoints under a shared URL prefix, and lets you apply configuration to all of them at once.

  • One call gives every endpoint in the group the same prefix, authorization, filters, rate limits and OpenAPI tags.
  • Groups nest, so the prefixes and the configuration both compound.
  • It is what makes minimal APIs viable at scale โ€” without it, every endpoint repeats the same setup.

Definitions

Term What it is What it means
MapGroup a method (.NET 7+) Creates a RouteGroupBuilder with a shared prefix.
RouteGroupBuilder a class What MapGroup returns. You call MapGet, MapPost and configuration methods on it.
Prefix a route template fragment Prepended to every endpoint's template in the group.
RequireAuthorization a method Applies an authorization policy to the whole group.
AddEndpointFilter a method Adds an endpoint filter to every endpoint in the group. See 12.7.
WithTags a method Groups endpoints under a heading in OpenAPI output.
WithOpenApi a method Adds or customises OpenAPI metadata.
RequireRateLimiting a method Applies a rate-limit policy to the group.
AllowAnonymous a method Opts an endpoint or nested group out of an inherited authorization requirement.
Nesting calling MapGroup on a group Prefixes concatenate and configuration accumulates.

The concept

The problem without groups

Minimal APIs are concise per endpoint and repetitive across them:

app.MapGet("/api/v1/orders", ListOrders)
   .RequireAuthorization("OrdersRead").WithTags("Orders").WithOpenApi();

app.MapGet("/api/v1/orders/{id:guid}", GetOrder)
   .RequireAuthorization("OrdersRead").WithTags("Orders").WithOpenApi();

app.MapPost("/api/v1/orders", CreateOrder)
   .RequireAuthorization("OrdersWrite").WithTags("Orders").WithOpenApi();

The prefix is repeated three times, the tag three times, the OpenAPI call three times. Add a fourth endpoint and you repeat it again โ€” and the day someone forgets RequireAuthorization, you have an unprotected endpoint that looks exactly like its neighbours.

That last risk is the real argument. Repetition is tedious; repetition of a security control is dangerous.

With groups

var orders = app.MapGroup("/api/v1/orders")
    .RequireAuthorization("OrdersRead")
    .WithTags("Orders")
    .WithOpenApi();

orders.MapGet("/", ListOrders);
orders.MapGet("/{id:guid}", GetOrder);
orders.MapPost("/", CreateOrder).RequireAuthorization("OrdersWrite");   // stricter

The prefix, tag and OpenAPI setup are stated once. A new endpoint added to the group inherits the authorization automatically โ€” you cannot forget it.

A picture: a folder with permissions set on it. Every file you drop in inherits them. You do not set permissions per file and hope nobody misses one.


How it works

The simple version

var group = app.MapGroup("/api/orders");

group.MapGet("/", ListOrders);                    // GET  /api/orders
group.MapGet("/{id:guid}", GetOrder);             // GET  /api/orders/{id}
group.MapPost("/", CreateOrder);                  // POST /api/orders
group.MapDelete("/{id:guid}", DeleteOrder);       // DELETE /api/orders/{id}

Prefixes concatenate with each endpoint's template. Note the "/" for the group root โ€” an empty string works too, but "/" reads more clearly.

What can be applied to a group

var admin = app.MapGroup("/api/admin")
    .RequireAuthorization("AdminOnly")             // authorization
    .RequireRateLimiting("strict")                 // rate limiting
    .AddEndpointFilter<AuditFilter>()              // filters
    .WithTags("Administration")                    // OpenAPI grouping
    .WithOpenApi()
    .RequireHost("admin.example.com");             // host constraint

Everything registered on that group gets all of it. This is what makes minimal APIs workable beyond a handful of endpoints.

Nesting

Groups nest, and both the prefix and the configuration compound:

var api = app.MapGroup("/api")
    .WithOpenApi();

var v1 = api.MapGroup("/v1")
    .WithTags("v1");

var orders = v1.MapGroup("/orders")
    .RequireAuthorization("OrdersRead");

orders.MapGet("/{id:guid}", GetOrder);
// โ†’ GET /api/v1/orders/{id}
// โ†’ OpenAPI enabled, tagged "v1", requires OrdersRead

Each level adds to what the level above established.

โš ๏ธ Escaping an inherited requirement

Authorization inherited from a group applies to everything below it โ€” including endpoints that should be public:

var api = app.MapGroup("/api").RequireAuthorization();

api.MapGet("/health", () => Results.Ok());        // โš ๏ธ now requires authentication

AllowAnonymous opts back out:

api.MapGet("/health", () => Results.Ok()).AllowAnonymous();       // โœ“ public again

โš ๏ธ AllowAnonymous wins over RequireAuthorization regardless of order, because it is metadata that the authorization middleware checks first. That is convenient and worth knowing โ€” it means you cannot "re-secure" an endpoint by adding RequireAuthorization after AllowAnonymous.

The safer structure is to make public endpoints a sibling group rather than a child, so nothing depends on remembering the opt-out:

var api    = app.MapGroup("/api");
var secure = api.MapGroup("").RequireAuthorization();     // everything under here is protected
var public_ = api.MapGroup("");                          // and here is not

secure.MapGet("/orders", ListOrders);
public_.MapGet("/health", () => Results.Ok());

How it actually works โ€” filters on a group

An endpoint filter added to a group runs for every endpoint in it (12.7):

public class ValidationFilter<T>(IValidator<T> validator) : IEndpointFilter
    where T : class
{
    public async ValueTask<object?> InvokeAsync(
        EndpointFilterInvocationContext context, EndpointFilterDelegate next)
    {
        var argument = context.Arguments.OfType<T>().FirstOrDefault();

        if (argument is not null)
        {
            var result = await validator.ValidateAsync(argument, context.HttpContext.RequestAborted);

            if (!result.IsValid)
                return Results.ValidationProblem(result.ToDictionary());
        }

        return await next(context);
    }
}
orders.MapPost("/", CreateOrder)
      .AddEndpointFilter<ValidationFilter<CreateOrderRequest>>();

โš ๏ธ Group filters run outermost-first, so a filter on /api runs before one on /api/orders, which runs before one on the endpoint. Same nesting model as middleware (5.1).

Groups versus controllers

Controllers Route groups
Grouping mechanism A class A MapGroup call
Shared prefix [Route] on the class The group prefix
Shared authorization [Authorize] on the class RequireAuthorization
Cross-cutting behaviour MVC filters Endpoint filters
Nesting โŒ No โœ… Yes
Model binding Full Slightly reduced
Native AOT โŒ Limited โœ… Supported

Route groups give minimal APIs the organisational benefits of controllers โ€” which is exactly what they were added for. Before .NET 7, "minimal APIs do not scale past a few endpoints" was a fair criticism; groups largely answered it.

โš ๏ธ Nesting is the one thing controllers cannot do. A controller cannot inherit a prefix and policy from a parent controller, so versioning plus grouping means repeating the version in every class's [Route].

The deeper detail โ€” organising a real API

โš ๏ธ A file of a hundred MapGet calls is no better than a thousand-line controller. The pattern that scales is one extension method per feature, next to that feature's code (4.11):

// Features/Orders/OrderEndpoints.cs
public static class OrderEndpoints
{
    public static RouteGroupBuilder MapOrderEndpoints(this IEndpointRouteBuilder app)
    {
        var group = app.MapGroup("/orders")
            .WithTags("Orders")
            .RequireAuthorization("OrdersRead");

        group.MapGet("/", ListOrders);
        group.MapGet("/{id:guid}", GetOrder).WithName("Orders_Get");
        group.MapPost("/", CreateOrder).RequireAuthorization("OrdersWrite");
        group.MapDelete("/{id:guid}", DeleteOrder).RequireAuthorization("OrdersDelete");

        return group;
    }

    private static async Task<IResult> GetOrder(
        Guid id, IOrderService orders, CancellationToken ct)
        => await orders.GetAsync(id, ct) is { } order
            ? TypedResults.Ok(order)
            : TypedResults.NotFound();

    // ...the other handlers
}
// Program.cs stays readable regardless of how many features exist
var v1 = app.MapGroup("/api/v1").WithOpenApi();

v1.MapOrderEndpoints();
v1.MapPaymentEndpoints();
v1.MapCustomerEndpoints();

Note the extension takes IEndpointRouteBuilder, not WebApplication โ€” that is what lets it be called on a group as well as on the app itself, which is what makes nesting work.


Code

A complete, realistically structured API:

var app = builder.Build();

app.UseAuthentication();
app.UseAuthorization();

// โ”€โ”€ Public, no authentication โ”€โ”€
var pub = app.MapGroup("/api/v1").WithOpenApi();
pub.MapGet("/health", () => TypedResults.Ok(new { status = "healthy" }))
   .AllowAnonymous()
   .ExcludeFromDescription();                     // keep it out of the OpenAPI doc

// โ”€โ”€ Authenticated โ”€โ”€
var api = app.MapGroup("/api/v1")
    .RequireAuthorization()
    .RequireRateLimiting("standard")
    .WithOpenApi();

api.MapOrderEndpoints();
api.MapCustomerEndpoints();

// โ”€โ”€ Admin: stricter policy, tighter rate limit, audited โ”€โ”€
var admin = app.MapGroup("/api/v1/admin")
    .RequireAuthorization("AdminOnly")
    .RequireRateLimiting("strict")
    .AddEndpointFilter<AuditFilter>()
    .WithTags("Administration")
    .WithOpenApi();

admin.MapUserManagementEndpoints();
admin.MapSystemEndpoints();

app.Run();

Two design points worth explaining:

Public endpoints are a separate group, not a child of the authenticated one with AllowAnonymous. That means a new endpoint added to api is protected by construction โ€” you cannot forget.

Admin is a sibling of api, not nested inside it. Nesting would apply both the standard and strict rate limits, which is not what you want. Keeping them siblings makes the policies explicit.

The versioned equivalent

var v1 = app.MapGroup("/api/v1").WithTags("v1").WithOpenApi();
var v2 = app.MapGroup("/api/v2").WithTags("v2").WithOpenApi();

v1.MapOrderEndpointsV1();
v2.MapOrderEndpointsV2();

Adding a version is one group and one extension method, with no duplication of the endpoint configuration (10.6).


Interview questions

Q: What are route groups and what problem do they solve?

MapGroup, added in .NET 7, collects related minimal API endpoints under a shared prefix and lets you apply configuration to all of them at once โ€” authorization, rate limiting, endpoint filters, OpenAPI tags. Without them, every endpoint repeats the same prefix and the same setup calls, which is tedious and, more importantly, risky: the day someone forgets RequireAuthorization on a new endpoint, you have an unprotected one that looks identical to its neighbours. With a group, new endpoints inherit it by construction.

Q: How does nesting work?

Groups can be created from other groups, and both the prefix and the configuration compound. So /api with OpenAPI enabled, then /v1 with a tag, then /orders with an authorization policy gives you /api/v1/orders carrying all three. That is one thing controllers cannot do โ€” a controller cannot inherit a prefix and policy from a parent controller, so versioning plus grouping means repeating the version in every class's route attribute.

Q: How do you make one endpoint in an authenticated group public?

AllowAnonymous on that endpoint, which wins over an inherited RequireAuthorization regardless of the order they were applied, because the authorization middleware checks that metadata first. I would generally prefer structuring it differently though โ€” making the public endpoints a sibling group rather than a child, so nothing depends on remembering the opt-out. Security by construction beats security by remembering.

Q: Do route groups make minimal APIs viable for a large API?

Largely, yes โ€” before .NET 7 "minimal APIs do not scale past a few endpoints" was a fair criticism, and groups answered most of it. The pattern that actually scales is one extension method per feature returning a configured group, called from Program.cs, so the startup file stays the same length whether you have three features or thirty. The extension should take IEndpointRouteBuilder rather than WebApplication, because that is what lets it be called on a group and therefore nested.


Traps โš ๏ธ

  • An endpoint in an authenticated group is protected, including ones you meant to be public. AllowAnonymous opts out.
  • AllowAnonymous wins regardless of order. You cannot re-secure an endpoint after it.
  • Nesting compounds configuration, so a nested group inherits the parent's rate limit as well as its own.
  • Group filters run outermost-first, like middleware.
  • A file of a hundred MapGet calls is as bad as a huge controller. Use one extension method per feature.
  • An extension method taking WebApplication cannot be called on a group. Take IEndpointRouteBuilder.
  • Groups are minimal APIs only. Controllers use [Route] and attributes instead.
  • The prefix concatenates literally, so a missing or doubled / produces a wrong URL.


Sources