Today we will look at minimal APIs, a new feature in .NET 6. In the past, we created controllers in order to create an API which could be consumed by our clients. In .NET 6, a new feature called Minimal APIs has been introduced. This allows us to create an API with minimum code and plumbing. In fact, it is created directly in the Program.cs file. In .NET 6, the Startup.cs file is also not required anymore, and all initial plumbing is done inside the Program.cs file. We will create a simple Minimal API. So, let us begin.
Creating Minimal APIs

Let us start by opening Visual Studio 2022. I use the community edition which is free to download and use.

Select “Create a new project”.


Select “ASP.NET Core Web API”.


 

Remember to uncheck the highlighted option to use minimal APIs


Open the “Program.cs” file and update as below,

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.MapGet("/welcomemessage", () => {
    return "Welcome to Minimal APIs";
}).WithName("GetWelcomeMessage");
app.Run();
internal record WeatherForecast(DateTime Date, int TemperatureC, string ? Summary) {
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}

Running the application
We now run the application and see the swagger page as below,

Here, we can try both the minimal APIs we have in our code.


 

In this article, we looked at creating a minimal API, a new feature in .NET 6. The example here was a simple one but it gives an idea of the concept and more complex APIs can be added. Probably for more complex APIs, refactoring into a separate file is a good idea. Happy coding!

HostForLIFE.eu ASP.NET Core Hosting

European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.