How to use the new minimal API features in ASP.NET Core 8

Parameter binding from forms, antiforgery tokens, and Native AOT are now supported in ASP.NET Core. Here’s how to take advantage of them.

shutterstock 2408848757 white light bulb and white sticks of chalk on bright yellow background
miregherban2 / Shutterstock

ASP.NET Core offers a simplified hosting model, called minimal APIs, that allows us to build lightweight APIs with minimal dependencies. Ideal for building fast and simple services, minimal APIs were initially introduced in ASP.NET Core 6 to strip away the complexity of traditional APIs and make it easier to build microservices.

The goal of this post is to explore the new features for building minimal APIs introduced in ASP.NET Core 8. To use the code examples provided in this article, you should have Visual Studio 2022 installed in your system. If you don’t already have a copy, you can download Visual Studio 2022 here.

Create an ASP.NET Core Web API project in Visual Studio 2022

To create an ASP.NET Core 8 Web API project in Visual Studio 2022, follow the steps outlined below.

  1. Launch the Visual Studio 2022 IDE.
  2. Click on “Create new project.”
  3. In the “Create new project” window, select “ASP.NET Core Web API” from the list of templates displayed.
  4. Click Next.
  5. In the “Configure your new project” window, specify the name and location for the new project. Optionally check the “Place solution and project in the same directory” check box, depending on your preferences.
  6. Click Next.
  7. In the “Additional Information” window shown next, select “.NET 8.0 (Long Term Support)” as the framework version and uncheck the check box that says “Use controllers,” as we’ll be using minimal APIs in this project.
  8. Elsewhere in the “Additional Information” window, leave the “Authentication Type” set to “None” (the default) and make sure the check boxes “Enable Open API Support,” “Configure for HTTPS,” and “Enable Docker” remain unchecked. We won’t be using any of those features here.
  9. Click Create.

We’ll use this ASP.NET Core Web API project to work with the code examples given in the sections below.

Create a minimal API in ASP.NET Core

You can replace the generated code with the following piece of code to create a minimal minimal API.

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

When you execute the application, the text “Hello World!” will be displayed in your web browser.

We’ll examine the new features in minimal API in the sections that follow.

Use model binding in minimal APIs

Support for FromForm binding was added to minimal APIs with ASP.NET Core 8. Before we explore FromForm binding, let’s take a quick look at the other types of model binding we can use in minimal APIs.

ASP.NET Core minimal APIs provide support for the following types of model binding:

  • FromBody binding
  • FromHeader binding
  • FromRoute binding
  • FromQuery binding
  • FromForm binding

With the new support for FromForm binding in minimal APIs, parameter binding from forms is now supported for collections such as lists and dictionaries and for complex types.

FromBody binding

FromBody binding extracts data from the body of the HTTP request and assigns it to parameters of your action methods. 

[HttpPost]
public IActionResult CreateAuthor([FromBody] Author author)
{
    //Usual code
}

FromHeader binding

FromHeader binding extracts data from the HTTP request headers and assigns it to parameters of your action methods.

[HttpGet]
public IActionResult GetAuthors([FromHeader("Authorization")] string authHeader)
{
    //Write your code here to validate the authorization token
}

FromRoute binding

FromRoute binding is used to retrieve data from request URL path segments and assign it to parameters of your action methods. You can use this type of model binding to identify a specific resource.

[HttpGet("{id}")]
public IActionResult GetAuthorById(int id)
{
    //Write your code here to retrieve an author instance based on id
}

FromQuery binding

FromQuery binding is used to retrieve data from the query string of an HTTP request and use it to populate a model object.

[HttpGet]
public ActionResult<List<Author>> GetAuthors([FromQuery] AuthorFilter filter)
{
    //Write code here to process the filter criteria and retrieve the list of filtered author records
}

FromForm binding

You can use FromForm binding to extract data from posted form fields in your minimal APIs. For example, the following code snippet illustrates how you can use the extracted parameters from a posted form to build a new Author instance.

[HttpPost]
public async Task<IActionResult> CreateAuthor([FromForm] Author author)
{
  //Usual code
}

Use antiforgery tokens in minimal APIs

ASP.NET Core 8 also brings support for antiforgery tokens to minimal APIs. To use this feature, you need to call the AddAntiForgery method to register antiforgery services with the request processing pipeline as shown in the code snippet given below.

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

The following code snippet shows how you can use antiforgery tokens in your minimal APIs.

app.MapGet("/", (HttpContext context, IAntiforgery antiforgery) =>
{
    var token = antiforgery.GetAndStoreTokens(context);
    return Results.Ok("Success...");
});

Use Native AOT in minimal APIs

You can directly compile .NET code into native code ahead of time (AOT) using the Native AOT capabilities supported by .NET Core. Pre-compiling will improve the startup time of your application because it eliminates the requirement for just-in-time (JIT) compilation during runtime.

You can now leverage Native AOT support in your minimal APIs in ASP.NET Core 8. To add support for Native AOT to your project, you should add the PublishAot property to your project file as shown in the code snippet below.

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

Note that you can also use the following command in the Visual Studio Developer Command Prompt to create a new minimal API project with Native AOT support enabled. Then you may pre-compile your ASP.NET Core minimal API assemblies into native code that will execute directly on the target system instead of bundling it with the .NET Core runtime.

dotnet new webapiaot

Minimal APIs in ASP.NET Core 9

In the ASP.NET Core ecosystem, the support for minimal APIs is being improved by the day. While .NET 9 is still in preview status, several new features have been added to minimal APIs in ASP.NET Core 9. I’ll discuss them in a future post here when the official release of ASP.NET Core 9 becomes available.

Copyright © 2024 IDG Communications, Inc.