Deep Dive into Minimal APIs in ASP.NET Core 8

Deep Dive into Minimal APIs in ASP.NET Core 8

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

  1. Minimal Configuration: No need for controllers, attributes, or dependency-heavy configurations.
  2. Route Handling Simplified: You define HTTP methods (GET, POST, PUT, DELETE, etc.) with Lambda expressions.
  3. Automatic Model Binding: Minimal APIs provide built-in support for binding request data to method parameters.
  4. Endpoint Filters: A powerful new feature in ASP.NET Core 8 for processing requests or responses globally or at specific endpoints.
  5. OpenAPI/Swagger Integration: Easily enable Swagger documentation even with minimal APIs.
  6. Dependency Injection (DI): Still supports all the powerful features of DI that ASP.NET Core offers.
  7. Lightweight and Fast: Since there’s less abstraction, Minimal APIs can be more performant, especially for small, focused tasks.

Why Choose Minimal APIs?

  • Faster Development: Minimal APIs reduce the need for extensive setup and configuration, speeding up the development process.
  • Lower Overhead: With less boilerplate code and fewer abstractions, Minimal APIs are lightweight and can perform better for small-scale services or microservices.
  • Flexible and Extensible: Minimal APIs still offer the flexibility of ASP.NET Core, including dependency injection, middleware, and integration with existing libraries.
  • Easier for Small Projects: Ideal for small, single-purpose APIs, microservices, or serverless applications that don't require the full MVC framework.

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:

  • MapGet: Defines a route for the HTTP GET request. When the root URL / is hit, it returns the message "Welcome to Minimal API in ASP.NET Core 8".

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:

  1. MapGet("/users"): Returns a list of users (for simplicity, just an array of strings).
  2. MapGet("/users/{id}"): Accepts a parameter id and returns the corresponding user ID.
  3. MapPost("/users"): Accepts a User object (model binding) and returns a "Created" response with a link to the newly created user.

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:

  • JWT authentication is added using AddJwtBearer.
  • The /secure route is protected by RequireAuthorization, ensuring that only authenticated users can access it.

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:

  • We define an endpoint filter that ensures a user's name is not empty before proceeding with the request.

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.

要查看或添加评论,请登录

Praful Chauhan的更多文章

社区洞察

其他会员也浏览了