Top-level statements– Minimal API
Before you begin: Join our book community on Discord
https://packt.link/EarlyAccess
This chapter covers Minimal APIs, a simplified way of setting up and running .NET applications. We explore what makes Minimal Hosting and Minimal APIs a pivotal update in ASP.NET Core as we unravel the simplicity of creating APIs with less ceremony. We cover many possibilities that ASP.NET Core Minimal API brings, like how to configure, customize, and organize those endpoints.We also explore using Minimal APIs with Data Transfer Objects (DTOs), combining simplicity with effective data management to structure API contracts effectively.Inspired by other technologies, these topics bring a fresh perspective to the .NET world, allowing us to build lean and performant APIs without compromising resiliency.In this chapter, we cover the following topics:
Let’s begin with Top-level statements.
The .NET team introduced top-level statements to the language in .NET 5 and C# 9. From that point, writing statements before declaring namespaces and other members is possible. Under the hood, the compiler emits those statements into a Program.Main method.With top-level statements, a minimal .NET “Hello World” console program looked like this (Program.cs):
using System;
Console.WriteLine(“Hello world!”);
Unfortunately, we still need a project to run it, so we have to create a .csproj file with the following content:
<Project Sdk=”Microsoft.NET.Sdk”>
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<OutputType>Exe</OutputType>
</PropertyGroup>
</Project>
From there, we can use the .NET CLI to dotnet run the application, and it will output the following in the console before the program terminates:
On top of such statements, we can also declare other members, like classes, and use them in our application. However, we must declare classes at the end of the top-level code.
Be aware that the top-level statement code is not part of any namespace, and creating classes in a namespace is recommended, so you should limit the number of declarations done in the Program.cs file to what is internal to its inner workings, if anything.
The highlighted line of the preceding C# code (using System;) is unnecessary when the implicit usings feature is enabled, which is the default in .NET 6+ projects. The templates add the following line to the .csproj file:
<ImplicitUsings>enable</ImplicitUsings>
Next, we explore the minimal hosting model built using top-level statements.