Transitioning from Controller to Minimal API in ASP.NET Core

Introduction

The ASP.NET Core framework has evolved significantly over the years, introducing new paradigms to streamline the development process. One of the most notable advancements in recent times is the introduction of Minimal APIs in .NET 6, which offer a simplified way to build APIs with less boilerplate code compared to traditional MVC controllers. This article explores the process of transitioning from the traditional Controller-based approach to using Minimal APIs, highlighting the benefits and providing practical examples.

Understanding Controllers in ASP.NET Core

In a traditional ASP.NET Core application, controllers are the cornerstone for handling HTTP requests. Each controller is a class that groups related actions, where each action corresponds to an endpoint.

Example of a Simple Controller

using Microsoft.AspNetCore.Mvc;

namespace MyApi.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        [HttpGet]
        public IEnumerable<WeatherForecast> Get()
        {
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
            .ToArray();
        }
    }
}

This example demonstrates a typical controller with a single HttpGet action that returns a list of weather forecasts.

Introducing Minimal APIs

Minimal APIs provide a new way to create HTTP APIs with minimal setup. They are designed to reduce the boilerplate code required for defining simple APIs, making the development process more efficient and straightforward.

Benefits of Minimal APIs

  1. Simplicity: Less boilerplate code and fewer files to manage.
  2. Performance: Reduced overhead compared to controllers.
  3. Flexibility: Easier to set up and use for small services or microservices.

Example of a Minimal API

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

var summaries = new[]
{
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

app.MapGet("/weatherforecast", () =>
{
    var rng = new Random();
    var forecast = Enumerable.Range(1, 5).Select(index => new WeatherForecast
    {
        Date = DateTime.Now.AddDays(index),
        TemperatureC = rng.Next(-20, 55),
        Summary = summaries[rng.Next(summaries.Length)]
    })
    .ToArray();
    return forecast;
});

app.Run();

public record WeatherForecast(DateTime Date, int TemperatureC, string Summary);

In this example, the entire setup, including endpoint definitions, is done in the Program.cs file, greatly simplifying the project structure.

Transitioning from Controllers to Minimal APIs

Transitioning from controllers to Minimal APIs involves several steps:

  1. Setup the WebApplication: Initialize the WebApplication as shown in the Minimal API example.
  2. Define Endpoints Directly: Replace controller methods with endpoint mappings using app.MapGet, app.MapPost, etc.
  3. Use Records for Models: Take advantage of C# records for simple data models, which align well with the functional style of Minimal APIs.
  4. Remove Unnecessary Boilerplate: Eliminate the need for [ApiController], [Route], and other attributes by directly mapping routes.

Step-by-Step Transition Example

Let's convert the earlier WeatherForecastController to a Minimal API:

  1. Initial Controller-Based Approach

    • WeatherForecastController is defined in the Controllers folder.
    • Model class WeatherForecast.
  2. Convert to Minimal API

    • Remove the Controllers folder and its content.
    • Modify Program.cs to include the endpoint definition.

Before (Controller-Based)

  • Controllers/WeatherForecastController.cs
  • Models/WeatherForecast.cs

After (Minimal API)

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

var summaries = new[]
{
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};

app.MapGet("/weatherforecast", () =>
{
    var rng = new Random();
    var forecast = Enumerable.Range(1, 5).Select(index => new WeatherForecast
    {
        Date = DateTime.Now.AddDays(index),
        TemperatureC = rng.Next(-20, 55),
        Summary = summaries[rng.Next(summaries.Length)]
    })
    .ToArray();
    return forecast;
});

app.Run();

public record WeatherForecast(DateTime Date, int TemperatureC, string Summary);

Conclusion

Transitioning from controllers to Minimal APIs in ASP.NET Core can significantly streamline your codebase, especially for small to medium-sized applications or microservices. While controllers provide robust functionality for larger applications with complex requirements, Minimal APIs offer a lightweight alternative that reduces complexity and improves performance. By understanding both paradigms, developers can choose the best approach for their specific needs, leveraging the strengths of each methodology.