Deep Dive into Minimal APIs in ASP.NET Core 8
Praful Chauhan
7+ Yrs | Full Stack Software Engineer | ReactJS | Redux | ASP.NET Core | Clean Architecture | Microservice | SQL | MongoDB | Postgres | Payment gateway integration | 3rd Party Supplier Integration
What is a Minimal API?
Minimal APIs were introduced in ASP.NET Core 6 and have been further enhanced in ASP.NET Core 8. Unlike traditional MVC-based APIs, Minimal APIs provide a lightweight and simplified approach for building HTTP services. They aim to reduce boilerplate code, allowing developers to create RESTful services using a more functional programming style.
In a Minimal API, you directly define routes and handle requests within the Program.cs file, without the need for controllers, attributes, or extensive configuration. This approach is ideal for microservices, serverless functions, and small services where you need quick, straightforward implementations.
Key Features of Minimal APIs in ASP.NET Core 8
Why Choose Minimal APIs?
Setting Up a Minimal API in ASP.NET Core 8
Let's walk through a complete example of how to set up a Minimal API from scratch in ASP.NET Core 8.
Step 1: Create a New ASP.NET Core 8 Project
Start by creating a new ASP.NET Core 8 project using the command line.
dotnet new web -n MinimalApiExample
cd MinimalApiExample
This template generates a basic web project, which you can modify to implement a minimal API.
Step 2: Basic Setup of a Minimal API in Program.cs
In ASP.NET Core 8, you define endpoints directly in the Program.cs file. Here's an example:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
// A simple GET request
app.MapGet("/", () => "Welcome to Minimal API in ASP.NET Core 8");
// Start the application
app.Run();
In this basic setup:
Step 3: Adding Multiple Routes and Parameterized Endpoints
You can add routes for different HTTP methods and include parameters in the routes to handle more complex operations.
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
// GET method to fetch all users
app.MapGet("/users", () =>
{
return new[] { "Alice", "Bob", "Charlie" };
});
// GET method with a parameter to fetch a user by ID
app.MapGet("/users/{id}", (int id) =>
{
return $"User ID: {id}";
});
// POST method to create a new user
app.MapPost("/users", (User newUser) =>
{
return Results.Created($"/users/{newUser.Id}", newUser);
});
// Start the application
app.Run();
// Define the User model
public record User(int Id, string Name, string Email);
Explanation:
领英推荐
Step 4: Adding Dependency Injection
You can still use all the ASP.NET Core features, such as Dependency Injection, with minimal APIs.
var builder = WebApplication.CreateBuilder(args);
// Add services to DI container
builder.Services.AddSingleton<IUserService, UserService>();
var app = builder.Build();
// GET method with DI
app.MapGet("/users", (IUserService userService) =>
{
return userService.GetAllUsers();
});
// Start the application
app.Run();
// Service and Interface
public interface IUserService
{
IEnumerable<string> GetAllUsers();
}
public class UserService : IUserService
{
public IEnumerable<string> GetAllUsers()
{
return new[] { "Alice", "Bob", "Charlie" };
}
}
Step 5: Adding Swagger for API Documentation
Even in Minimal APIs, you can easily integrate Swagger to generate API documentation.
Add the Swashbuckle.AspNetCore NuGet package for Swagger.
dotnet add package Swashbuckle.AspNetCore
Next, configure Swagger in Program.cs:
var builder = WebApplication.CreateBuilder(args);
// Add Swagger services
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Enable Swagger
app.UseSwagger();
app.UseSwaggerUI();
// Define minimal API routes
app.MapGet("/", () => "Hello, World!");
// Start the app
app.Run();
Now, when you run the application, Swagger documentation will be available at /swagger in the browser.
Step 6: Adding Authentication and Authorization
Minimal APIs also support authentication and authorization. Here’s a basic example using JWT authentication.
var builder = WebApplication.CreateBuilder(args);
// Add JWT authentication
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.Authority = "https://your-auth-server";
options.Audience = "your-api-audience";
});
builder.Services.AddAuthorization();
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
// A protected API route
app.MapGet("/secure", () => "This is a protected resource")
.RequireAuthorization();
app.Run();
In this example:
Step 7: Leveraging Endpoint Filters (New in ASP.NET Core 8)
Endpoint filters in ASP.NET Core 8 allow you to define reusable logic that can be applied to multiple endpoints. This could include validation, logging, or modifying the request/response.
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
// Define an endpoint filter
app.MapPost("/users", (User newUser) =>
{
return Results.Created($"/users/{newUser.Id}", newUser);
}).AddEndpointFilter(async (context, next) =>
{
var user = context.GetArgument<User>(0);
if (string.IsNullOrEmpty(user.Name))
{
return Results.BadRequest("Name is required");
}
return await next(context);
});
app.Run();
// User model
public record User(int Id, string Name, string Email);
In this example:
Conclusion
Minimal APIs in ASP.NET Core 8 provide a streamlined and efficient way to build small-scale web services. They reduce the overhead of traditional MVC patterns while still retaining the full power of ASP.NET Core's middleware, dependency injection, and other features. Whether you're building microservices, serverless functions, or just want a lightweight API for quick tasks, Minimal APIs offer a flexible and easy-to-use solution.