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(); })
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();
We can use partial Program.cs files too
Example: "Program.Users.cs"
partial class Program
{
/// <summary>
/// Map all users routes
/// </summary>
/// <param name="app"></param>
private static void AddUsers(WebApplication app)
{
app.MapGet("/users", () => "All users");
app.MapGet("/user/{id?}", (int? id) => $"A users {id}");
///post, patch, delete...
}
}
And in "Program.cs"
...
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
//add...
AddUsers(app);
...