ASP.NET Core – True Ultimate Guide
Section 30: Minimal API
Minimal APIs in ASP.NET Core
Minimal APIs in ASP.NET Core allow you to create HTTP APIs with minimal code and configuration. They simplify the process of building APIs by reducing the boilerplate code typically required with traditional controller-based approaches.
1. Minimal API Overview
Minimal APIs provide a streamlined way to define routes and handle HTTP requests directly in the Program.cs file, eliminating the need for controllers and action methods. This approach is especially useful for small microservices or applications where you want to reduce overhead.
2. Defining Minimal APIs
Basic Example:
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/hello", () => "Hello, world!");
app.Run();MapGet: Maps an HTTP GET request to a handler. In this example, a request to/helloreturns the string “Hello, world!“.
3. Route Parameters
You can define route parameters to capture values from the URL and use them in your handlers.
app.MapGet("/greet/{name}", (string name) => $"Hello, {name}!");{name}: Captures the route parameter from the URL. Accessing/greet/Alicereturns “Hello, Alice!“.
4. MapGroups
MapGroups is used to group related routes together, helping to organize routes that share a common prefix.
app.MapGroup("/api")
.MapGet("/products", () => new[] { "Product1", "Product2" })
.MapGet("/orders", () => new[] { "Order1", "Order2" });MapGroup: Groups routes under the/apiprefix. Routes map to endpoints such as/api/productsand/api/orders.
5. IResult
IResult represents the result of an HTTP request and can be used to return various types of responses.
app.MapGet("/status", () =>
{
return Results.Ok(new { Status = "Running" }); // Return 200 OK with JSON response
});Common IResult methods:
Results.Ok(): 200 OKResults.NotFound(): 404 Not FoundResults.BadRequest(): 400 Bad RequestResults.Created(): 201 Created
6. Endpoint Filters
Endpoint filters allow you to run custom logic before or after the request handler is executed. They can be used for tasks like validation, logging, or authentication.
public class LoggingFilter : IEndpointFilter
{
public Task<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterInvocationDelegate next)
{
Console.WriteLine("Handling request...");
return next(context);
}
}
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/data", () => "Some data")
.AddEndpointFilter<LoggingFilter>();
app.Run();IEndpointFilter: Interface used to create filters that can be added to endpoints.
7. IEndpointFilter Interface
The IEndpointFilter interface is used to create custom filters that can be applied to endpoints. This allows you to inject logic into the request processing pipeline.
public class CustomFilter : IEndpointFilter
{
public Task<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterInvocationDelegate next)
{
// Custom logic before request handling
Console.WriteLine("Custom filter logic before handler.");
// Call the next filter or endpoint
var result = next(context);
// Custom logic after request handling
Console.WriteLine("Custom filter logic after handler.");
return result;
}
}Key Points to Remember
- Minimal APIs: Simplify API development with direct route and handler definitions in
Program.cs. - Route Parameters: Use
{param}syntax to capture values from URLs. - MapGroups: Group related routes under a common prefix for better organization.
- IResult: Return various HTTP responses using built-in methods like
Results.Ok,Results.NotFound, etc. - Endpoint Filters: Implement custom logic in request handling using
IEndpointFilter.