How to Use the New Minimal API Features in ASP.NET Core

By FoxLearn 12/31/2024 2:17:54 AM   90
In ASP.NET Core 8, several new features have been introduced to enhance the development of minimal APIs.

Creating a Minimal API in ASP.NET Core

To create a minimal API in ASP.NET Core, you can use the following code:

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => "Hello, World!");
app.Run();

When this application is executed, it will display "Hello, World!" in your browser.

New features of minimal APIs in ASP.NET Core 8

Model Binding in Minimal APIs

ASP.NET Core 8 introduces support for FromForm binding in minimal APIs. This allows data from posted form fields to be extracted and used in your methods.

FromBody Binding: Extracts data from the body of the HTTP request. 

[HttpPost]
public IActionResult CreateItem([FromBody] Item item)
{
    // Code to create an item
}

FromHeader Binding: Extracts data from the HTTP request headers.

[HttpGet]
public IActionResult GetItems([FromHeader("Authorization")] string token)
{
    // Validate authorization token
}

FromRoute Binding: Retrieves data from the URL path.

[HttpGet("{id}")]
public IActionResult GetItemById(int id)
{
    // Retrieve item by ID
}

FromQuery Binding: Extracts data from the query string.

[HttpGet]
public IActionResult GetItems([FromQuery] ItemFilter filter)
{
    // Process the filter and fetch items
}

FromForm Binding: Extracts data from posted form fields.

[HttpPost]
public async Task<IActionResult> CreateItem([FromForm] Item item)
{
    // Code to create an item using form data
}

Using Antiforgery Tokens

ASP.NET Core 8 also adds support for antiforgery tokens in minimal APIs. Antiforgery tokens help protect against cross-site request forgery (CSRF) attacks.

To use antiforgery tokens, you must register antiforgery services in the request pipeline as follows:

var builder = WebApplication.CreateBuilder();
builder.Services.AddAntiforgery();
var app = builder.Build();
app.MapGet("/", (HttpContext context, IAntiforgery antiforgery) =>
{
    var token = antiforgery.GetAndStoreTokens(context);
    return Results.Ok("Token generated successfully.");
});
app.Run();

This code generates and stores antiforgery tokens for the session.

Leveraging Native AOT

Native Ahead-of-Time (AOT) compilation is now supported in ASP.NET Core 8. With Native AOT, you can pre-compile your .NET code into native machine code, improving the application's startup performance by eliminating Just-In-Time (JIT) compilation.

To enable Native AOT in your project, add the following to your .csproj file:

<PropertyGroup>
  <PublishAot>true</PublishAot>
</PropertyGroup>

Alternatively, you can create a new minimal API project with Native AOT support enabled using the command:

dotnet new webapiaot

This ensures that your application is compiled into native code, making it faster to start and reducing runtime overhead.

ASP.NET Core 8 brings exciting new features to minimal APIs, such as form data binding, antiforgery token support, and Native AOT compilation. These features make minimal APIs even more powerful and efficient for building fast, secure, and lightweight APIs, particularly for microservices.