Introduction to. Net Minimal Api

Minimal API is a new template in. Net 6. With the help of some features of C# 10, it runs a Web service with minimal code. This paper breaks away from VS and completes the development of a simple minimal API project through VS Code.

Create project

Create a new folder to manage our project files. Start the command line in the folder and create the project through 'dotnet new web'.

  It's still a pile of files. When a Program.cs file can run a Web project, maybe one day

Run project

Execute 'dotnet run' under the project directory to run the project.

Try to play some flowers with the web version VS Code( https://vscode.dev/ )Run the project, but it's not as strong as I thought. It's not supported yet.

 Coding

The builder instance provides the Services attribute, which can complete the registration of Services in the ConfigureServices method of the original Startup class, and some Use operations of the Configure method are completed through app.

builder.Services.AddMemoryCache();

//todo
 app.UseStaticFiles();
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", $"{builder.Environment.ApplicationName} v1"));
}

MapGet variant

Route mapping is realized through the MapGet method of the app instance generated by Build.

app.MapGet("/", () => "Hello World!");
//app.Map("/",[HttpGet] () => "Hello World!");
//app.MapMethods("/", new List<string>() { HttpMethod.Get.ToString() }, () => "Hello World!");

You can see that the corresponding features can be added directly before the Delegate through the Delegate method. async keyword can also be marked directly before Delegate.

Routing mapping is almost interesting. Different versions cannot be managed like other language frameworks, such as:

var api = app.Part("v1",middleware);
api.MapGet("", () =>{ return ""; });

Application

Directly modify the application configuration in the code, such as modifying the listening port

app.Urls.Add("http://localhost:3000");
//app.Urls.Add("http://localhost:4000");
//app.Run();
app.Run("http://localhost:4000");

  Priority app. Run > app. URLs. Add >   launchSettings

Dependency Injection

Constructor injection cannot be used in the Minimal API. It can be injected through parameters, and the tag of the FromServices attribute can be ignored.

Context

The context information of some Http requests can also be specified directly through parameters and used directly in the method body instead of the Request in MVC. For example:

  • HttpContext
  • HttpRequest
  • HttpResponse
  • ClaimsPrincipal
  • CancellationToken
app.MapGet("/context", (HttpContext httpContext) => new 
{
    Data = httpContext.Connection.Id
});

More type References: github

Responses

The static class Results returns the corresponding type of the standard to achieve the same effect as the corresponding method provided by ControllerBase.

app.MapGet("/ok/{id}", (int id) =>
{
    return Results.Ok($"ok:{id}");
});

Link Generation

You can configure the route through the extension method WithXXX, for example, specify the name through WithName, and then produce the corresponding Uri through LinkGenerator to avoid hard coding

app.MapGet("/context", (HttpContext httpContext) => new
{
    Data = httpContext.Connection.Id
}).WithName("hi");
app.MapGet("hello", (LinkGenerator linker) =>
        $"The link to the hello route is {linker.GetPathByName("hi", values: null)}");

In addition to some column RoutingEndpointConvention extension methods such as WithXXX, authorization endpointconvention related extension methods RequireAuthorization and AllowAnonymous are also provided to replace the related features in MVC mode (the feature can also be supported by one more support method).

This article only lists some simple usages of the Minimal API, and integrates Swagger and other usages. Refer to: https://minimal-apis.github.io/hello-minimal/

The return status code and type of the interface can be described through the extension method productions, such as: productions < responsemode > (contenttype: "application / XML"), however Interface remarks It doesn't seem to support it yet. I tried many ways and couldn't display it correctly.

Code Format

The problem with the above example of the minimum API is that there are too many codes in the Program file, and the mapping and response of all routes are together. Although the response method can be extracted by using the static method as follows, all route maps are listed together and cannot be separated like the Controller.

var handler = new HelloHandler();

app.MapGet("/", handler.Hello);

class HelloHandler
{
    public string Hello() 
    {
        return "Hello World";
    }
}

Open source framework MASA.Contrib The provided masa.contrib.service.minimaapis completes the code encapsulation.

Detailed usage reference MASA.EShop

Keywords: .NET

Added by kumarrana on Sun, 07 Nov 2021 04:05:27 +0200