June 06, 2021 by Anuraj Estimated read time : 8 mins
This article will discuss about minimal APIs in ASP.NET Core 6.0. For a developer coming from Python or Node eco system - the dotnet or dotnet core environment will be over whelming. Minimal APIs will help new developers to build their first ASP.NET Core apps with less ceremony. This will also helps developers to build small microservices and HTTP APIs. This feature is released as part of .NET Core 6.0 Preview 4 - which released along with Microsoft Build 2021 few days back. To get started, you need to create an ASP.NET Core empty web app, you can do this with the command dotnet new web. Once you created the project you will get a directory structure like this.
Let’s open the Program.cs file. It will be like this.
In case of ASP.NET Core 5.0, same command will generate following code. For demo purposes I combined both Program.cs and Startup.cs code.
If you look 43 lines of code reduced to 15 lines. And unlike the old versions there is no static void main() method in Program.cs. It is called Top-level programs it is a feature as part of C# 9.0. You can find more details about this in this blog post.
Another improvement is new routing APIs - with this feature developers can route to any type of method - These methods can use controller-like parameter binding, JSON formatting, and action result execution. In earlier version of ASP.NET Core writing the Hello World string to browser done via this code snippet.
But now it is reduced to app.MapGet("/", (Func<string>)(() => "Hello World!")); - with more C# 10 features this code can be reduced something like app.MapGet("/", (() => "Hello World!"));. Also in C# 10.0 you can provide attributes to lambda expressions.
Here is a CRUD Web API app with Minimal APIs.
Now you have learned about Minimal APIs in ASP.NET Core. Right now you need a project file also to build a minimal API project. The dotnet core SDK is planning to compile single source file with dotnet run command. You can find more details here.