1
头图

.NET 6, which Microsoft calls "the fastest .NET yet," comes with many exciting new features, language and performance improvements. This is the first LTS release since .NET Core 3.1 and will be supported for three years. This major release adds a new feature: Minimal APIs, what technology is this?

.NET6 makes it easy to write REST APIs with minimal dependencies.

Minimal APIs seem to be Microsoft's answer to the NodeJS (using ExpressJS) HTTP server, which provides a minimal API. But Microsoft also added a few key words to the technology:

summarizes one sentence: .NET 6 Minimal APIs simplifies the design and implementation of HTTP Rest APIs, allowing developers to quickly and efficiently implement HTTP Rest APIs.

Today, we take a moment to research and popularize the .NET 6 Minimal APIs.

look at the sample code for .NET 6 Minimal APIs

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/", () => "Hello World!");

app.Run();

In the above example, the app.MapGet method uses an inline lambda expression to complete the business logic of a Controller Action, which is really super simple.
Super simple definition of an HTTP WebAPI: no more Startup.cs, API controllers, extra dependencies, etc.

Only these 4 lines of code are required to generate the following output:

Explore some of the techniques behind this code

The above code, on Microsoft's official documentation, recommends that you use VS2022, in fact, VS Code can also be used

Tutorial: Create a minimal web API with ASP.NET Core

But the machine must first install the .NET 6 SDK

After the installation is complete, open VS Code, create a new terminal, and create a Web Project

dotnet new web -o MyMinimalAPI

In the code project, we can see:

There is no using in the Program.cs class, and of course there is no main function. Let me explain to you here:

① .NET5 introduces Top-Level Class, there is no main function, and the code is executed as a direct entry

② .NET 6 added a great new feature - "implicit global use"

Automatically generate invisible using statements and declare them globally, so you don't have to deal with the clutter of repeating namespaces in every file.

Let's open MyMinimalAPI.csproj to see what's inside, there is a configuration:

<ImplicitUsings>enable</ImplicitUsings>

After dotnet build, find the obj/Debug/net6.0 folder to see the hidden autogenerated file - [ProjectName].GlobalUsings.g.cs. Use a separate class to keep all using statements in one place.

With this feature, we don't need to repeat namespace using references in every file. It's really convenient and simple.

Of course, if you don't want to use this feature, you can disable the ImplicitUsings flag in the .csproj file.

In the above example, the app.MapGet method uses an inline lambda expression. Also provides:

app.MapPost()
app.MapPut()
app.MapDelete()

Next, we use a simple example to complete a demo.

Complete a Minimal APIs Complete Demo

Let's take a simple Order as an example to implement CRUD design and implementation through Minimal APIs:

▌Prepare the Order class, IOrderService interface and OrderServiceRepository

Order class:



namespace NET6
{
    public class Order
    {
        public int ID {get;set;}

        public decimal  Price  {get;set;}

        public string CustomAddress {get;set;}

        public int State{get;set;}
    }
}

IOrderService interface:

namespace NET6
{
    public interface IOrderService
    {
         Order GetOrder(int id);

         void CreateOrder(Order order);

         void DeleteOrder(int id);

         void UpdateOrder(Order order);
    }
}

The OrderServiceRepository class implements the data storage layer using an in-memory collection simulation.

namespace NET6
{
    public class OrderServiceRepository : IOrderService
    {
        static List<Order> orders = new List<Order>();

        public Order GetOrder(int id)
        {
            return orders.FirstOrDefault(i=>i.ID == id)?? null;
        }

        public void CreateOrder(Order order)
        {
            orders.Add(order);
        }

        public void DeleteOrder(int id)
        {
            var order = orders.FirstOrDefault(i=>i.ID == id);
            if(order!=null)
            orders.Remove(order);
        }

        public void UpdateOrder(Order order)
        {
            DeleteOrder(order.ID);
            CreateOrder(order);
        }
    }
}

▌In the Program.cs class, register the IOrderService service, add AddOrder and GetOrder Http Web API

using NET6;

var builder = WebApplication.CreateBuilder(args);

//registe IOrderService service
builder.Services.AddScoped<IOrderService, OrderServiceRepository>();

var app = builder.Build();

app.MapGet("/", () => "Hello World!");

//add order save API
app.MapPost("/add",(Order order,IOrderService service)=>
{   
    service.CreateOrder(order);
}).WithName("addorder");

//add order query API
app.MapGet("/getorder",(int id, IOrderService service)=>
{       
    return service.GetOrder(id);
}).WithName("getorder");

app.Run();

In the above low code, first add a file-level namespace, this place is to show the difference between Global Namespace and everyone

using NET6;

Then, add the IOrderService service in the ASP.NET DI dependency injection framework:​​​​​​​

//registe IOrderService service
builder.Services.AddScoped<IOrderService, OrderServiceRepository>();

Add order order save API service:​​​​​​​

//add order save API
app.MapPost("/add",(Order order,IOrderService service)=>
{   
    service.CreateOrder(order);
}).WithName("addorder");

In the above HttpWebAPI, we use the Post method, and the request must pass in the order parameter.

In this code, we see that the save order method has two parameters, one is Order and the other is IOrderService. The second parameter supports dependency injection natively and does not need to be explicitly created.

Similarly, continue to add query order API service​​​​​​​

//add order query API
app.MapGet("/getorder",(int id, IOrderService service)=>
{       
    return service.GetOrder(id);
}).WithName("getorder");

▌Run and debug

Enter the dotnet run command in the terminal to start running debugging

dotnet run

To debug these 3 APIs, it is recommended that you use the PostMan tool

Let’s talk about a small pit first. At the beginning, I used the PostMan tool to debug the save order interface, and put the explicit parameters of the order into the headers to request, but the result has not worked:

After reading Microsoft's sample documents, it is recommended to directly use the order json object and the http request body to initiate the request in raw mode

Other API interfaces do not have this problem:

The above is a brief introduction and practice of .NET 6 Minimal APIs, I hope it can help you.

view using ASP.NET Core to create Minimal Web API


微软技术栈
418 声望994 粉丝

微软技术生态官方平台。予力众生,成就不凡!微软致力于用技术改变世界,助力企业实现数字化转型。