Exploring Minimal APIs in .NET 7: Advantages and Comparison with Traditional Web APIs
Paul Nichols
Expert Azure Certified Senior Integration Specialist with 25+ years of experience delivering secure, efficient solutions for government and enterprise clients
Introduction
.NET 6 introduced Minimal APIs, a powerful and efficient alternative to traditional web APIs in ASP.NET Core. As the .NET platform evolves with .NET 7, we can expect further enhancements and refinements to Minimal APIs, making them an increasingly appealing choice for building modern web applications. This article delves into Minimal APIs, discussing their advantages and suitable use cases. Additionally, we will compare Minimal APIs with traditional web APIs to help you make informed decisions about which approach best suits your needs.
A Closer Look at Minimal APIs
Minimal APIs are an innovative feature in ASP.NET Core designed to simplify web API creation by minimising the amount of boilerplate code required to set up an API. Developers can define HTTP endpoints using a concise and expressive C# syntax. With Minimal APIs, the focus is on the essential functionality of your API, while the framework handles common tasks such as routing, dependency injection, and middleware configuration.
New Features in .NET 7
.NET 7 brings several improvements and new features to Minimal APIs, making them nearly as powerful as traditional controllers. Some of the new features include:
Performance Improvements in .NET 7
.NET 7 brings significant performance improvements to the ASP.NET Core platform, which also benefits Minimal APIs. One of the key enhancements is support for HTTP/2, a more efficient version of the HTTP protocol that allows for faster uploads and downloads. However, to avoid any single connection from using too much memory on the server, there is still a connection-level limit on how many bytes can be sent at a time. These performance improvements, combined with the streamlined syntax and reduced overhead of Minimal APIs, make them an attractive option for building high-performance web APIs.
Key Advantages of Minimal APIs
Minimal API Examples
Below are some examples of Minimal APIs to help you understand their simplicity and ease of use.
Example 1: Basic "Hello World!" API
var app = WebApplication.Create(args);
app.MapGet("/", () => "Hello World!");
app.Run();
Example 2: API with Route Parameters
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/users/{userId}/books/{bookId}",
(int userId, int bookId) => $"The user id is {userId} and book id is {bookId}");
app.Run();
Example 3: Fetching Data from a Database
app.MapGet("/books", async (BooksDB db) => await db.Books.ToListAsync());
Example 4: API with OpenAPI Specification Support
领英推荐
app.MapGet("/books", async (BooksDB db) => await db.Books.ToListAsync())
.Produces<List<Book>>(StatusCodes.Status200OK)
.WithName("GetAllBooks")
.WithTags("Getters");
These examples demonstrate the power and simplicity of Minimal APIs in ASP.NET Core. You can use them to create fully functioning REST endpoints with minimal code and configuration, bypassing the need for traditional scaffolding and controllers.
Working with File Data in Minimal APIs
Starting from .NET 7, Minimal APIs support more advanced actions, such as file processing. This enhancement allows you to upload files to an API endpoint by simply adding an?IFormFile?parameter to the endpoint method. Here's an example of an endpoint that uploads a text file, with each line representing a new TODO item to be inserted:
app.MapPost("/todos/upload", (IFormFile file,
[FromServices] ITodosRepository repository) =>
{
using var reader = new StreamReader(file.OpenReadStream());
while (reader.Peek() >= 0)
repository.InsertTodo(reader.ReadLine() ?? string.Empty);
});
In this example, reading from the uploaded file is as simple as calling the?OpenReadStream?method on the?IFormFile?implementation. You can then check if any lines are remaining by calling the?Peek?method on the stream. If there are any lines, you can read the next line by calling the?ReadLine?method.
Binding the Request Body as a Stream or PipeReader
Minimal APIs allow you to bind the request body as a?Stream?or?PipeReader?for efficient processing and storage of data. This is useful when you need to store data in blob storage or enqueue data to a queue provider, such as Azure Queue storage or Azure Blob storage. Here's an example of how to bind the request body as a?ReadOnlyMemory<byte>?and deserialize it using?JsonSerializer:
using System.Text.Json;
using System.Threading.Channels;
namespace BackgroundQueueService;
class BackgroundQueue : BackgroundService
{
private readonly Channel<ReadOnlyMemory<byte>> _queue;
private readonly ILogger<BackgroundQueue> _logger;
public BackgroundQueue(Channel<ReadOnlyMemory<byte>> queue,
ILogger<BackgroundQueue> logger)
{
_queue = queue;
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
await foreach (var dataStream in _queue.Reader.ReadAllAsync(stoppingToken))
{
try
{
var person = JsonSerializer.Deserialize<Person>(dataStream.Span)!;
_logger.LogInformation($"{person.Name} is {person.Age} " +
$"years and from {person.Country}");
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
}
}
}
}
class Person
{
public string Name { get; set; } = String.Empty;
public int Age { get; set; }
public string Country { get; set; } = String.Empty;
}
Allowing Unauthenticated Users to Access an Endpoint
You can use the?[AllowAnonymous]?attribute to allow unauthenticated users to access specific endpoints. This attribute can be applied to an endpoint method or chained to an endpoint using the AllowAnonymous()?method. Here are two examples of how to allow unauthenticated access to an endpoint:
app.MapGet("/login", [AllowAnonymous] () => "This endpoint is for all roles.");
app.MapGet("/login2", () => "This endpoint also for all roles.")
.AllowAnonymous();
Comparing Minimal APIs with Traditional Web APIs
When deciding between Minimal APIs and traditional Web APIs, you should consider the following factors:
Conclusion
In conclusion, the choice between Minimal APIs and traditional Web APIs depends on your project requirements and desired trade-offs. Minimal APIs are great for lightweight, simple projects and offer slightly better performance, while traditional Web APIs are better for projects that require advanced features and more control over the API implementation.