Search code examples
c#asp.net-core.net-6.0minimal-apis

Minimal API in .NET 6 using multiple files


In .NET 6 it is possible to create minimal APIs:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/products/{id}", (int id) => { return Results.Ok(); })
app.MapGet("/users/{id}", (int id) => { return Results.Ok(); })

app.Run();

What would be an approach to group endpoints in multiple files instead of having all in Program file?

ProductEndpoints.cs:

app.MapGet("/products/{id}", (int id) => { return Results.Ok(); })

UserEndpoints.cs

app.MapGet("/users/{id}", (int id) => { return Results.Ok(); })

Solution

  • Only one file with top-level statement is allowed per project. But nobody forbids moving endpoints to some static method of another class:

    public static class ProductEndpointsExt
    {
        public static void MapProductEndpoints(this WebApplication app)
        {
            app.MapGet("/products/{id}", (int id) => { return Results.Ok(); });
        }
    }
    

    And in the Program file:

    app.MapProductEndpoints();