.NET 6 introduces a more straightforward way to create APIs that can be very handy to power up prototypes or small projects you don’t want to deal with all the boilerplate you were required to write. Of course, you can enhance it gradually as you need.
Hands-On
I’ve added the NET6.Features.MinimalAPI
project by just using the following command:
1
$ dotnet new web -n NET6.Features.MinimalAPI
And that created a very minimalistic Microsoft.NET.Sdk.Web
project, without the Startup.cs
we’re used to, but only the Program.cs
.
Top-level statements
Top-level statements were actually introduced by C# 9
with .NET 5
. As the name suggests, it allows us to create C# statements at the top-level, which means without explicitly creating classes and namespaces. Check the documentation to see the capabilities and limitations.
Code structure
All the elements we need for a simple API will be there. Firstly the builder
is created from the builder.Build();
return object, and we effectively have our configured Web Application. This object will allow us to add services as we will see further, as to map our routes
.
Now all we need to return the Hello World!” string from the HTTP GET
route above is the last app.Run();
statement.
Swagger
I made some small changes with the endpoints that will bring the same records I used with the other articles from this series. Also, I added the Swashbuckle.AspNetCore
nuget package which comes with the known app.UseSwagger();
and app.UseSwaggerUI()
extension methods, and that’s all we need to have the following result.