.NET 6: Minimal APIs Explained

Minimal APIs are the biggest shift in ASP.NET Core since version 1.0. They remove the MVC ceremony (Controllers, Actions, Filters) in favor of a fluent lambda-based syntax.

The Code

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

app.MapGet("/", () => "Hello World");

app.MapGet("/users/{id}", async (int id, UserContext db) => 
    await db.Users.FindAsync(id) is User user 
        ? Results.Ok(user) 
        : Results.NotFound());

app.MapPost("/users", async (User user, UserContext db) => {
    db.Users.Add(user);
    await db.SaveChangesAsync();
    return Results.Created($"/users/{user.Id}", user);
});

app.Run();

Is it just for tiny apps?

No. Performance is technically better than MVC (fewer allocations, no Filter Pipeline overhead). However, organization becomes the challenge. You don’t want a 5,000 line `Program.cs`.

Structuring Minimal APIs

I recommend using extension methods to group routes:

// Program.cs
app.MapUserRoutes();
app.MapOrderRoutes();

// UserRoutes.cs
public static class UserRoutes 
{
    public static void MapUserRoutes(this WebApplication app) 
    {
        app.MapGet("/users", ...);
    }
}

Discover more from C4: Container, Code, Cloud & Context

Subscribe to get the latest posts sent to your email.

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.