Minimal Minimum API
In this article we will create an api using the new .net-6 feature called the "Minimum API" and use an absolute minimum of files we can get away with to create an example. To follow along you will need .Net-6 installed on your computer:
Create a new folder called mmapi, open it in your editor of choice such as VS Code. Now create a new file and call it minimal.csproj. This is our project file written in XML which is used to configure our project. These files can get big on some projects but for this example we just need to specify the framework we are targeting. So copy the following XML into the file:
<Project Sdk="Microsoft.NET.Sdk.Web">
? ? <PropertyGroup>
? ? ? ? <TargetFramework>net6.0</TargetFramework>
? ? ? ? <ImplicitUsings>enable</ImplicitUsings>
? ? </PropertyGroup>
</Project>
We will also need a file to hold our code for our hello world example though with this being a minimum app we will make it a hi ??, this will be called program.cs. The program.cs file is the default file to be run in dotnet and is where the code to initialise and application goes.?Copy the following code into the program.cs file:
领英推荐
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
app.MapGet("/", () => “Hi ??!");
app.Run();
In 4 lines of code we have created an app that will handle get requests and return Hello World. The above example also shows another dotnet6 feature called?top level statements, this allows us to avoid the normal boiler plate code of defining a class and a static main method and dive straight into the code we want to run for this example.
To see this in action go into a command line and build the code with:
dotnet build
dotnet run
You will see a message similar to: Now listening on:?https://localhost:5000?appear on the command line, view that url in a browser and?you will see Hi ??! appear.?