ASP.NET Core Web API Authentication with JWT
A complete JWT authentication setup for ASP.NET Core — issuing tokens, protecting endpoints, and role-based authorization.
ASP.NET Core's minimal API style (introduced in .NET 6, refined through .NET 10) strips away a lot of the ceremony older .NET developers remember from full MVC controllers. Here's the fastest real path to a working, production-reasonable API.
dotnet new webapi -n MyApi -minimal
cd MyApi
dotnet run
var app = WebApplication.Create(args);
app.MapGet("/posts", () => Results.Ok(posts));
app.MapGet("/posts/{id}", (int id) =>
{
var post = posts.FirstOrDefault(p => p.Id == id);
return post is not null ? Results.Ok(post) : Results.NotFound();
});
app.MapPost("/posts", (CreatePostDto dto) =>
{
var post = new Post(posts.Count + 1, dto.Title, dto.Body);
posts.Add(post);
return Results.Created($"/posts/{post.Id}", post);
});
app.Run();
No controller classes, no attribute routing — just direct route-to-handler mappings, which is exactly what most CRUD endpoints actually need.
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseNpgsql(builder.Configuration.GetConnectionString("Default")));
app.MapGet("/posts", async (AppDbContext db) =>
await db.Posts.ToListAsync());
EF Core's DbContext is registered once and injected directly into route handlers — the same dependency injection pattern that runs through the entire .NET ecosystem.
public class CreatePostValidator : AbstractValidator<CreatePostDto>
{
public CreatePostValidator()
{
RuleFor(x => x.Title).NotEmpty().MaximumLength(255);
}
}
Minimal APIs stay clean for small-to-medium services, but once you have dozens of endpoints, group related ones into extension methods (app.MapPostEndpoints()) rather than one giant Program.cs file. The underlying request pipeline, DI container, and middleware system are identical to full MVC — you're only opting out of controller classes, not out of ASP.NET Core's actual architecture.
A complete JWT authentication setup for ASP.NET Core — issuing tokens, protecting endpoints, and role-based authorization.
Creating, applying, and safely rolling back EF Core migrations — the .NET equivalent of Laravel migrations, and where the workflow differs.
Structuring an ASP.NET Core app so business logic has zero dependency on frameworks or databases — Domain, Application, Infrastructure, and Web layers.