Csharpessentials endpoints

From senrecep/CSharpEssentials · View interactive version

Csharpessentials endpoints is an AI agent skill from the GitHub repository senrecep/CSharpEssentials. Use when organizing ASP.NET Core Minimal API endpoints into classes. Covers IEndpoint/IEndpointGroup with a static Map, [EndpointGroup<T>] nesting, the source-generated Map{Assembly}Endpoints/MapAllEndpoints registry (AOT-safe), EndpointMappingOptions, RouteOf<T>, RequireRoles/RequirePolicies/Requir

How to use this skill

Skill file

CSharpEssentials.Endpoints

Source-generated endpoint organization for Minimal APIs. Route calls (MapGet, MapPost and so on) stay in your code, so binding, filters, IResult, OpenAPI and the Request Delegate Generator work unchanged. A generator emits one registry per assembly; no reflection runs at startup, so it is trim and Native AOT safe.

Installation

dotnet add package CSharpEssentials.Endpoints

Target frameworks: net11.0, net10.0, net9.0, net8.0. The source generator, analyzer and code fix ship in the package.

Namespace

using CSharpEssentials.Endpoints;

Generated registries live in Microsoft.AspNetCore.Builder, so app.Map{Asm}Endpoints() needs no extra using.


Endpoints and groups

public sealed class AppsGroup : IEndpointGroup
{
    public static string Prefix => "apps";

    public static void Configure(RouteGroupBuilder group) => group.WithTags("Apps").RequireAuthorization();
}

[EndpointGroup<AppsGroup>]
public sealed class GetApp : IEndpoint
{
    public static void Map(IEndpointRouteBuilder app) =>
        app.MapGet("/{id:int}", (int id, IAppService service) => service.GetAsync(id));
}

[EndpointGroup(typeof(AppsGroup))]
public sealed class CreateApp : IEndpoint
{
    public static void Map(IEndpointRouteBuilder app) =>
        app.MapPost("/", (CreateAppRequest request, IAppService service) => service.CreateAsync(request))
           .WithValidation<CreateAppRequest>()   // CSharpEssentials.AspNetCore + CSharpEssentials.Validation
           .RequireRoles("admin", "editor");
}

| Member | Rule |

|---|---|

| IEndpoint.Map(IEndpointRouteBuilder) | static abstract. Endpoint types are never instantiated; take dependencies as handler parameters. One type may map several routes. A non-partial type must declare static Map itself; one that only inherits it is not mapped (CSE1012). |

| IEndpointGroup.Prefix | static abstract string, passed to MapGroup. An empty string adds no segment. |

| IEndpointGroup.Configure(RouteGroupBuilder) | static virtual, optional. Group-wide tags, authorization, filters. |

| [EndpointGroup(typeof(T))] / [EndpointGroup<T>] | Places an endpoint or a group under a group. Groups nest. One group attribute per type. |

| [ExcludeFromMapping] | On an endpoint, a group (and everything under it) or an assembly. |


Mapping

app.MapAppsEndpoints();   // one assembly's registry
app.MapAllEndpoints();    // own registry + every referenced assembly's registry; call once per route builder, a repeat maps every route twice

IReadOnlyList<Type> mapped = AppsEndpointRegistry.EndpointTypes;   // mapping order

Mapping options

app.MapAppsEndpoints(options =>
{
    options.Filter(type => type.Namespace != "Sample.Internal");   // AND-combined predicates
    options.OperationNaming = OperationNaming.TypeName;            // None (default), TypeName, Custom(...)
    options.AutoTagFromGroup = true;                               // UsersGroup -> "Users" when no tags
    options.LogDiscovered = true;                                  // Debug log, category CSharpEssentials.Endpoints
    options.ConfigureEach((endpoint, type) => endpoint.WithMetadata(new AuditedEndpoint(type)));
});

Every endpoint gets EndpointTypeMetadata (EndpointType property) so middleware and tests can identify the endpoint type at runtime.

OperationNaming.TypeName:


Typed routes, authorization, versioning

string path = app.RouteOf<GetApp>(new { id = 42 });                 // "/apps/42"
string remove = app.RouteOf<AppCommands>("DELETE", new { id = 42 }); // select by HTTP method or WithName(...)

RouteGroupBuilder admin = app.MapGroup("admin")
    .RequireRoles("admin")              // any listed role
    .RequirePolicies("CanRead")         // every listed policy
    .RequireAuthSchemes("Bearer");      // any listed scheme

app.MapVersionedGroup(2).MapAppsEndpoints();   // CSharpEssentials.AspNetCore: routes under /v2/...

Reflection fallback

For assemblies without a generated registry (for example plugins loaded at runtime):

app.MapEndpointsFromAssemblies(typeof(Program).Assembly);
app.MapEndpointsFromAssemblies(options => options.LogDiscovered = true, pluginAssembly);

Same discovery rules, ordering and options as the generated registries. Types the analyzer reports as errors are skipped and logged at Warning. Marked [RequiresUnreferencedCode] and [RequiresDynamicCode], so not for trimmed or Native AOT apps; under Native AOT it throws PlatformNotSupportedException.


Diagnostics

| ID | Severity | Rule |

|---|---|---|

| CSE1001 | Error | Endpoint or group type is not accessible from generated code. |

| CSE1002 | Error | Group nesting cycle. |

| CSE1003 | Error | More than one group attribute on one type. |

| CSE1004 | Warning | Endpoint declares instance state (fields, auto-properties, constructor parameters). Code fix removes unused state. |

| CSE1005 | Warning | Two endpoints in the same group map the same HTTP method and constant route. |

| CSE1006 | Info | Abstract or open-generic endpoint or group type is skipped. |

| CSE1007 | Error | [EndpointGroup(typeof(X))] target does not implement IEndpointGroup, or is abstract, open-generic or a ref struct. |

| CSE1008 | Error | Endpoint or group type is a ref struct. Generated code passes it as a generic type argument, which ref structs cannot be, so it is not mapped. |

| CSE1009 | Warning | Two referenced assemblies produce the same registry name (Foo.Api and FooApi → FooApiEndpointRegistry); MapAllEndpoints skips both until one sets [assembly: EndpointRegistryName("...")]. When the own registry has the same name as a referenced one, only the own registry is mapped. |

| CSE1010 | Warning | The same constant endpoint name is set at two call sites (WithName, or EndpointNameAttribute/EndpointNameMetadata/RouteNameMetadata in WithMetadata). Endpoint names and route names are compared separately. |

| CSE1011 | Info | An explicit endpoint name outside an IEndpoint/IEndpointGroup type is not a constant, so it cannot be reserved at build time. |

| CSE1012 | Warning | A non-partial endpoint class inherits Map from a base class and does not declare it, so the generator does not map it. Make it partial or declare public static new void Map(IEndpointRouteBuilder app) => Base.Map(app);. |


Best practices

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.