Minimal APIs vs API Controllers

Minimal APIs vs API Controllers in .NET: ASP.NET Core offers two distinct paradigms for authoring HTTP web services: Minimal APIs and Controller-Based APIs.

ASP.NET Core offers two distinct paradigms for authoring HTTP web services: Minimal APIs and Controller-Based APIs. Choosing the right architecture is essential for building scalable, high-throughput microservices.


1. Deep Comparison: Minimal APIs vs Traditional Controllers

┌──────────────────────┬────────────────────────────────────┬────────────────────────────────────┐
│ Feature              │ Minimal APIs                       │ Controller-Based APIs (MVC)        │
├──────────────────────┼────────────────────────────────────┼────────────────────────────────────┤
│ Memory Allocation    │ ~30% Lower heap allocation         │ Higher (Controller instantiation)  │
│ Requests Per Second  │ Higher raw throughput              │ Moderate throughput                │
│ Architectural Style  │ Vertical Slice Architecture        │ Traditional N-Tier / Layered MVC   │
│ Endpoint Definition  │ Lambda expressions & Route Groups  │ Classes inheriting ControllerBase  │
│ Middleware Overhead  │ Bypasses MVC filter pipeline       │ Full MVC action filter pipeline    │
│ Ideal Use Case       │ Cloud Microservices, High RPS APIs │ Large enterprise legacy codebases  │
└──────────────────────┴────────────────────────────────────┴────────────────────────────────────┘

2. Complete Minimal API Implementation (Full CRUD Example)

Minimal APIs define endpoints directly on WebApplication or modular RouteGroupBuilder instances.

Organizing Endpoints with Route Groups:

// Program.cs
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped<ICourseRepository, CourseRepository>();
builder.Services.AddValidatorsFromAssemblyContaining<Program>();

var app = builder.Build();

// Group all course endpoints under "/api/v1/courses"
var coursesGroup = app.MapGroup("/api/v1/courses")
                      .WithTags("Courses")
                      .RequireRateLimiting("FixedPolicy");

// 1. GET: Query all courses with pagination
coursesGroup.MapGet("/", async (int page, int pageSize, ICourseRepository repo, CancellationToken ct) =>
{
    var courses = await repo.GetPagedAsync(page, pageSize, ct);
    return TypedResults.Ok(courses);
})
.WithName("GetAllCourses")
.Produces<List<CourseDto>>(StatusCodes.Status200OK);

// 2. GET: By ID with Route Constraints
coursesGroup.MapGet("/{id:guid}", async (Guid id, ICourseRepository repo, CancellationToken ct) =>
{
    var course = await repo.GetByIdAsync(id, ct);
    return course is not null 
        ? TypedResults.Ok(course) 
        : TypedResults.NotFound(new { Message = $"Course {id} was not found." });
})
.WithName("GetCourseById")
.Produces<CourseDto>(StatusCodes.Status200OK)
.Produces(StatusCodes.Status404NotFound);

// 3. POST: Create with validation
coursesGroup.MapPost("/", async (CreateCourseDto dto, IValidator<CreateCourseDto> validator, ICourseRepository repo, CancellationToken ct) =>
{
    var validationResult = await validator.ValidateAsync(dto, ct);
    if (!validationResult.IsValid)
    {
        return Results.ValidationProblem(validationResult.ToDictionary());
    }

    var createdCourse = await repo.CreateAsync(dto, ct);
    return TypedResults.Created($"/api/v1/courses/{createdCourse.Id}", createdCourse);
})
.WithName("CreateCourse")
.Produces<CourseDto>(StatusCodes.Status201Created)
.ProducesValidationProblem();

// 4. DELETE: With Authorization
coursesGroup.MapDelete("/{id:guid}", async (Guid id, ICourseRepository repo, CancellationToken ct) =>
{
    var deleted = await repo.DeleteAsync(id, ct);
    return deleted ? TypedResults.NoContent() : TypedResults.NotFound();
})
.RequireAuthorization("AdminOnly");

app.Run();

3. Strongly-Typed Results (TypedResults)

In earlier .NET versions, endpoints returned loosely-typed IResult via Results.Ok(). .NET 8 introduces TypedResults, which provides compile-time type safety for unit testing without needing mocks:

// Returns Results<Ok<CourseDto>, NotFound>
public static async Task<Results<Ok<CourseDto>, NotFound>> GetCourse(Guid id, ICourseRepository repo)
{
    var course = await repo.GetByIdAsync(id);
    return course is not null 
        ? TypedResults.Ok(course) 
        : TypedResults.NotFound();
}

4. Input Validation using FluentValidation

Never trust client input. Implement clean, decoupled validation rules:

public record CreateCourseDto(string Title, string Slug, decimal Price);

public class CreateCourseValidator : AbstractValidator<CreateCourseDto>
{
    public CreateCourseValidator()
    {
        RuleFor(x => x.Title)
            .NotEmpty().WithMessage("Course title is mandatory.")
            .MaximumLength(150).WithMessage("Title cannot exceed 150 characters.");

        RuleFor(x => x.Slug)
            .NotEmpty()
            .Matches("^[a-z0-9-]+$").WithMessage("Slug must be lowercase alphanumeric with hyphens.");

        RuleFor(x => x.Price)
            .GreaterThanOrEqualTo(0).WithMessage("Price must be zero or positive.");
    }
}

5. Traditional Controller Comparison

For contrast, here is the exact same logic written as a traditional MVC Controller:

[ApiController]
[Route("api/v1/[controller]")]
public class CoursesController : ControllerBase
{
    private readonly ICourseRepository _repo;

    public CoursesController(ICourseRepository repo)
    {
        _repo = repo;
    }

    [HttpGet("{id:guid}")]
    [ProducesResponseType(typeof(CourseDto), StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status404NotFound)]
    public async Task<ActionResult<CourseDto>> GetById(Guid id, CancellationToken ct)
    {
        var course = await _repo.GetByIdAsync(id, ct);
        if (course is null) return NotFound();
        return Ok(course);
    }
}