Skip to content

AspNetCore Route Policies

SteffenBlake edited this page Sep 28, 2026 · 1 revision

Route policies

A route policy configures ASP.NET Core endpoints as routes are registered. Use policies for shared authorization requirements, tags, and other RouteHandlerBuilder metadata.

The policy interfaces are in Brigade.Net.Partie.Engines.AspNetCore. Their methods receive RouteHandlerBuilder from Microsoft.AspNetCore.Builder.

Configure query routes

Implement IQueryRoutePolicy<TQuery> with static void Query(RouteHandlerBuilder route):

// CourseAuthorizationRoutePolicy.cs
public sealed class CourseAuthorizationRoutePolicy<TQuery> : IQueryRoutePolicy<TQuery>
{
    public static void Query(RouteHandlerBuilder route)
    {
        route.RequireAuthorization("CourseReaders");
        route.WithTags("Courses");
    }
}

Register the named authorization policy in your ASP.NET Core application, then apply the generated class-name attribute:

[BrigadeGroup("/courses")]
[CourseAuthorizationRoutePolicy]
public static partial class CourseRoutes
{
    [CourseSearchHandlerRoute.Get("/{courseId}")]
    public static partial void Search();
}

The query endpoint receives the CourseReaders requirement and the Courses tag. ASP.NET Core enforces the authorization requirement when requests arrive. The Partie policy method itself runs during endpoint registration.

Configure command routes

Commands use ICommandRoutePolicy<TCommand> and static void Command(RouteHandlerBuilder route):

// CourseWriteRoutePolicy.cs
public sealed class CourseWriteRoutePolicy<TCommand> : ICommandRoutePolicy<TCommand>
{
    public static void Command(RouteHandlerBuilder route)
    {
        route.RequireAuthorization("CourseWriters");
    }
}

Apply [CourseWriteRoutePolicy] to the group or command route. A query-only policy does not configure commands, and a command-only policy does not configure queries.

Select matching requests

A concrete request type limits a policy to that exact request. A generic parameter lets it apply across request types, and a constraint narrows that set:

public sealed class CourseReadRoutePolicy<TQuery> : IQueryRoutePolicy<TQuery>
    where TQuery : CourseQuery
{
    public static void Query(RouteHandlerBuilder route)
    {
        route.WithTags("Courses");
    }
}

Here, CourseQuery is your application's base query class. Only queries satisfying the constraint receive the policy. See Generic matching for exact matching and constraints.

Configuration order

Policies run from the outer group to inner groups, then route policies, then the route method body. A route body can add endpoint-specific metadata after the shared configuration. How repeated metadata combines depends on the ASP.NET Core builder method you call.

Use a Partie for work that needs the bound request or a per-request context. Use a route policy for endpoint configuration shared by several declarations.

Clone this wiki locally