Home > database >  Minimal API in .NET 6 using multiple files
Minimal API in .NET 6 using multiple files

Time:11-28

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(); })

CodePudding user response:

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();
  • Related