Web API on .NET 6

Binod Mahto
3 min readNov 18, 2021

--

.NET 6 is released on Nov 8th 2021 claiming that, .NET 6 is the fasted .NET yet and available with visual studio 2022 along with C# 10 for development.

Lets see what has changed from .NET 5 to .NET 6 for web API developer.

  1. Minimal APIs
    It is new template introduced to create APIs with minimal dependencies. if you are familiar with other high level languages to build APIs like Python, NodeJs etc. then you might see it as familiar concept.
    This option you have to choose while creating new project to get the template.

Default is controller based APIs and I would prefer that personally for better code separation and manageability purpose but here you have to uncheck the option to get the minimal API template.

How your APIs will look like for Minimal APIs template:

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");//this is your function name
internal record WeatherForecast(DateTime Date, int TemperatureC, string? Summary)
{
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}

In above code, it shows how you have to write your GET api.

2. All new C# 9.0 and 10.0 features.

When you create the new .NET 6 web api project (here i’m going with controller option for APIs), below are the changes you would notice:
i. No more Startup.cs class file used for configuring your services and middlewares.

ii. No more static void Main(string[] args) method in Program.cs. Though this is the basic concept which we have learned so far as the only starting point for execution.

iii. Lines of code with no method in Program.cs but no compile time error.

Let’s see the code once.

using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Identity.Web;
var builder = WebApplication.CreateBuilder(args);
builder.Host.ConfigureAppConfiguration((hostingContext, config) =>
{
var env = hostingContext.HostingEnvironment;
config.AddIniFile("MyAppConfig.json", optional: true, reloadOnChange: true)
.AddIniFile($"MyAppConfig.{env.EnvironmentName}.json",
optional: true, reloadOnChange: true);
});
// Add services to the container.
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));
builder.Services.AddControllers();
// 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();app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();app.Run();

Here is the explanation to calm down you curiosity for above mentioned points related to above code here.

i. NO Startup.cs file because all the code has been moved to Program.cs by simplifying the .NET Core APIs to call those extra methods in Startup class to configure services and middlewares.

ii. NO Main() method because here .NET 6 is using the feature “Top Level Statements” introduced in C# 9.0 where all top level lines of codes will be considered as code belongs to Main() method for execution. it’s very common features for languages like jQuery, Python, NodeJS etc. But the catch is, those line of code must be part of Program.cs file or any other file if Program.cs doesn’t exists (in short you can have only one .cs file to contain top level statements). if notice, in the template .NET started using record type (introduce in C# 9)instead of class type as it happens in .NET 5 api template.

iii. Above explains why no methods in Program.cs file as all are considered part of Main() method and will be executed in the order it is defined, mark this statement as order is important.

iv. .NET 6 has redefined some of the APIs, one example which I noticed related to “ConfigureAppConfiguration” method which we used to add custom configs, resources etc to the core application. Now you can do in this way in program.cs file.

var builder = WebApplication.CreateBuilder(args);
builder.Host.ConfigureAppConfiguration((hostingContext, config) =>
{
var env = hostingContext.HostingEnvironment;
config.AddIniFile("MyAppConfig.json", optional: true, reloadOnChange: true)
.AddIniFile($"MyAppConfig.{env.EnvironmentName}.json",
optional: true, reloadOnChange: true);
});

Thank You for reading, Hope you enjoyed it. Please don’t forget the clap (as much you want) for this and subscribe to get update on my next article.

--

--

Binod Mahto

Solution Architect & Full Stack Developer. Passionate about Software designing & development and Learning Technologies and Love to share what I learn.