As a .NET developer, you are no stranger to building web applications using ASP.NET Core. With the introduction of ASP.NET Core 6, Microsoft has provided developers with two distinct approaches to building APIs: Minimal APIs and Controller APIs. In this article, we will explore both types, understand their pros and cons, and discuss scenarios where you might choose one over the other.
ASP.NET Core Minimal API
Minimal APIs are a lightweight and streamlined way to build web APIs in ASP.NET Core. They are designed to make API development faster and more concise.
Minimal APIs allow you to define routes and handle requests using a single file, often referred to as a “Program.cs” file.
As Microsoft describes them:
The design of minimal APIs hides the host class by default and focuses on configuration and extensibility via extension methods that take functions as lambda expressions.
Let’s dive into an example of building a Minimal API.
Minimal API Implementation Example
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Hosting;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.MapGet("/hello", () => "Hello, Minimal API!");
app.MapPost("/greet", async (HttpContext context) =>
{
using var reader = new StreamReader(context.Request.Body);
var requestContent = await reader.ReadToEndAsync();
return $"Received POST request with content: {requestContent}";
});
app.Run();
It is pretty straight forward, right? Using the MapGet function, we have defined a function that handles the GET request to the “/hello” endpoint, which gives back a string.
Using the MapPost function, we’ve added a POST request handler for the “/greet” endpoint, which reads the request body and returns a response with the body of the request added to it.
Pros
- Minimal Boilerplate: Minimal APIs require less code and fewer files compared to traditional controller-based APIs. This can lead to quicker development and easier maintenance.
- Faster Startup: Due to their lightweight nature, Minimal APIs have faster startup times, making them suitable for microservices and serverless architectures.
- Functional Approach: Minimal APIs embrace a functional approach, allowing developers to define routes and handlers using a more functional and expressive syntax.
Cons
- Limited Features: Minimal APIs may not offer as many built-in features and conventions as Controller APIs. You might need to implement certain functionality manually.
Useful Resources
Check out these resources to read more about Minimal APIs for your ASP.NET Core project:
ASP.NET Core Controller API
Controller APIs are the traditional approach to building APIs in ASP.NET Core. They rely on controllers, which are classes responsible for handling HTTP requests and returning responses. Controllers give a more structured way of implementing your API, but also require more understanding of how to set them up properly.
As Microsoft describes them:
Controllers are classes that can take dependencies via constructor injection or property injection, and generally follow object-oriented patterns.
Let’s look at a simple example showing a controller-based implementation.
Controller API Implementation Example
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
[Route("api/[controller]")]
[ApiController]
public class GreetingController : ControllerBase
{
private readonly ILogger<GreetingController> _logger;
public GreetingController(ILogger<GreetingController> logger)
{
_logger = logger;
}
[HttpGet]
public IActionResult Get()
{
return Ok("Hello, Controller API!");
}
[HttpPost]
public IActionResult Post([FromBody] string content)
{
if (string.IsNullOrEmpty(content))
{
return BadRequest("Request content cannot be empty.");
}
// Process the content as needed
_logger.LogInformation($"Received POST request with content: {content}");
return Ok($"Received POST request with content: {content}");
}
}
In this example, I’ve mimicked the implementation of the Minimal API code example. I’ve added simple functionality to the POST handler function, to check if the content is empty, and which writes logging.
I wanted to show you the logger as with a controller class, it is easy to use dependency injection to add dependant functionality in its constructor, which can be used to quickly expand the API controller’s functionality. In this example, it was done for logging.
Pros
- Rich Features: Controller APIs offer a wide range of features, such as model binding, validation, action filters, and routing attributes. These features can be especially helpful in complex applications.
- Convention Over Configuration: Controller APIs follow a convention-based approach, reducing the need for explicit configuration. This can lead to a more structured and organized codebase.
- Ecosystem Support: Controller APIs have been around for a while, which means there are extensive resources, libraries, and community support available.
Cons
- Boilerplate Code: Building Controller APIs often involves writing more code and creating additional files, which can slow down development.
- Slower Startup: Controller APIs may have slightly longer startup times compared to Minimal APIs, making them less suitable for scenarios requiring rapid scaling.
Useful Resources
Check out these resources to read more about implementing Controller APIs for your ASP.NET Core project:
- Microsoft’s official Learn documentation
- Yogi Hosting tutorial on How to Create WEb APIs in ASP.Net Core
When to Choose Minimal API vs. Controller API
Now that we understand the characteristics of both types, let’s discuss when to choose each variant.
But before I dive into reasons to choose between the one or another, I’d love to emphasize that you are allowed and can implement both ways in your solution. For instance, when you have a full-blown function API for a web application, and you want to expand the API by adding a basically smaller subset of functionality (i.e.: for internal use in your company), ASP.NET Core allows you to mingle both.
Make sure these kinds of decisions are clear when you are working with a team of developers, so everyone understands why you’ve chosen the Minimal-, Controller-, or a combination of both API implementations.
Reasons to favour Minimal API
- You need a quick and lightweight solution for a simple API or microservice.
- Fast startup times are critical for your application.
- You prefer a functional and minimalistic coding style.
- You want to reduce boilerplate code and keep your codebase concise.
Choose Controller API When
- You are working on a complex API with advanced features like model validation and custom action filters.
- Convention-based routing and extensive attribute support are beneficial for your project.
- You have an existing codebase that follows the Controller API pattern.
- You need the full feature set and ecosystem support provided by Controller APIs.
Conclusion
In the world of ASP.NET Core, the choice between Minimal APIs and Controller APIs boils down to the specific needs of your project. Minimal APIs offer speed and simplicity, while Controller APIs provide a robust and feature-rich environment. Consider your project requirements, development team’s familiarity, and long-term goals when making this decision.
To recap what we’ve discussed:
- You’ve seen the definition and a code example of both a Minimal- and Controller-based API implementation
- Minimal APIs are quick, lightweight, and minimalistic. Ideal for simple APIs and microservices
- Controller APIs are feature-rich, convention-based, and suited for complex and/or more structured applications
In the end, both Minimal APIs and Controller APIs have their place in ASP.NET Core development, and the right choice depends on the unique demands of your project.
Let me know in the comments or hit that ♥️ if you liked my article. I'm curious what kind of API implementation you use most often and for what scenario.
Code Hard, Ship Harder
.NET Developers, increase your productivity when working with databases: LINQ Me Up - Convert SQL into LINQ Code, vice versa and create LINQ code from your data samples
Top comments (0)