Minimal API in .NET 6

.NET 6 is released on November 9th. Microsoft provides a lot of new features and improvements:

  • C# 10
  • Hot Reload
  • Blazor components rendering from JavaScript
  • WebAssembly AOT
  • dotnet monitor & OpenTelemetry support
  • HTTP/3 & OpenSSL 3 support
  • File IO symbolic links support
  • Source generators and analyzers

As a part of the .NET 6 release, Microsoft added Minimal API support.

Minimal API is a great way for beginners to create small microservices and HTTP APIs using C# and ASP.NET Core.

Hosting and routing capabilities contain the minimum set of components needed to build API with less configuration and dependencies.

The developers could write a fully functioning API with just a few lines of code using new C# 10 features (global usings, file-scoped namespaces, top-level statements, etc.).

Minimal API is an alternative to the traditional ASP.NET Core MVC framework for building modern and complex web applications. It has become much easier to create lightweight APIs without MVC and use only specific features. It’s not the replacement of ASP.NET Core MVC but another way with just minimal middlewares, routings, dependencies, and configurations under the hood.

Let’s create our first Minimal API project. Open any terminal and run the following command:

dotnet new  webapi -minimal -o MinimalApiSample

Let’s open the newly created project in VisualStudio 2022 or VisualStudio Code and start examining the project structure and code.

As you can see from the image below the Minimal API project contains only three files:

No alt text provided for this image
  • Program.cs
  • appsettings.json
  • launchSettings.json

The Program.cs contains the following lines of code:

var builder = WebApplication.CreateBuilder(args)


// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();


var app = builder.Build();


// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}


app.UseHttpsRedirection();


var summaries = new[]
{
    "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};


app.MapGet("/weatherforecast", () =>
{
    var forecast =  Enumerable.Range(1, 5).Select(index =>
        new WeatherForecast
        (
            DateTime.Now.AddDays(index),
            Random.Shared.Next(-20, 55),
            summaries[Random.Shared.Next(summaries.Length)]
        ))
        .ToArray();
    return forecast;
})
.WithName("GetWeatherForecast");


app.Run();


record WeatherForecast(DateTime Date, int TemperatureC, string? Summary)
{
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
};

By default, the project template contains Swagger support and is configured for a development environment.

builder.Services.AddEndpointsApiExplorer()
builder.Services.AddSwaggerGen();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

The MinimalApiSample.csproj contains the following lines of code:

<Project Sdk="Microsoft.NET.Sdk.Web"


  <PropertyGroup>
    <TargetFramework>net6.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
  </PropertyGroup>


  <ItemGroup>
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
  </ItemGroup>


</Project>

>

We can see that the target framework shown in our project is .NET 6.

<TargetFramework>net6.0</TargetFramework>

Also by default, Minimal API project templates contain nullable and implicit using support.

<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>

The package reference includes Swashbuckle.AspNetCore support.

<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />

Let’s update our project to create really Minimal API.

Remove Swashbuckle.AspNetCore dependency from MinimalApiSample.csproj and update the lines that contain launchUrl in launchSettings.json as follows:

"launchUrl": ""

Replace the contents of the Program.cs with the minimum code required to launch our Minimal API as follows:

var builder = WebApplication.CreateBuilder(args)
var app = builder.Build();
app.MapGet("/", () => "Hello Minimal API!");
await app.RunAsync();

Run the app. Hello Minimal API! is displayed.

Additional Resources

Written by Serhii Kokhan, .Net Arhitect

Comments are closed.