Controllers and minimal API

Both Controllers and Minimal APIs are ways to build web APIs in .NET, but they represent different approaches with distinct advantages and use cases.

Controllers

Features

Controllers offer a wide range of features, including:

1. Action Filters: Attributes that modify the behavior of actions (e.g., authorization, caching).

Understanding Action Filters (C#)

The goal of this tutorial is to explain action filters. An action filter is an attribute that you can apply to learn.microsoft.com.

2. Model Binding: Automatic conversion of request data into .NET objects.

Model Binding in ASP.NET Core

Learn how model binding in ASP.NET Core works and how to customize its behavior: learn.microsoft.com

3. Dependency Injection: Seamless integration with the .NET dependency injection system.

4. Routing: Flexible routing options to define how requests are mapped to actions.

Example

[ApiController]
[Route("[controller]")]
public class ProductsController : ControllerBase
{
    private readonly IProductService _productService;

    public ProductsController(IProductService productService)
    {
        _productService = productService;
    }

    [HttpGet("{id}")]
    public async Task<IActionResult> GetProduct(int id)
    {
        var product = await _productService.GetProductByIdAsync(id);
        if (product == null)
        {
            return NotFound();
        }
        return Ok(product);
    }
}

Minimal API’s

Minimal API is Microsoft’s attempt to respond to JavaScript's so-called “simple API”.

Minimal APIs overview

An introduction to the fastest and easiest way to create web API endpoints with ASP.NET Core: learn.microsoft.com

Key Features

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

app.MapGet("/products/{id}", async (int id, IProductService productService) =>
{
    var product = await productService.GetProductByIdAsync(id);
    if (product == null)
    {
        return Results.NotFound();
    }
    return Results.Ok(product);
});

app.Run();

Choosing Between Controllers and Minimal APIs

Use Controllers when

Use Minimal APIs when

Consider these factors when making your decision

Summary

One is not better than the other.