当前位置:网站首页>Introduction to minimal API
Introduction to minimal API
2022-06-26 16:46:00 【Masa technical team】
Minimal APIs yes .Net 6 New template in , With the help of C# 10 Some features of run a with minimal code Web service . Article separation VS adopt VS Code, Complete a simple Minimal Api Project development .
Create project
Create a new folder , Used to manage our project files , Start the command line in the folder , adopt dotnet new web Create project .
Minimal├── obj├── Properties├── appsettings.Development.json├── appsettings.json├── Minimal.csproj└── Program.csRun the project
Execute under project directory dotnet run, Run the project .
PS C:\Users\User01\Desktop\Minimal> dotnet run Generating ...info: Microsoft.Hosting.Lifetime[14] Now listening on: https://localhost:7221info: Microsoft.Hosting.Lifetime[14] Now listening on: http://localhost:5252info: Microsoft.Hosting.Lifetime[0] Application started. Press Ctrl+C to shut down.info: Microsoft.Hosting.Lifetime[0] Hosting environment: Developmentinfo: Microsoft.Hosting.Lifetime[0] Content root path: C:\Users\User01\Desktop\Minimal\The operation effect is as follows :

Coding
builder Examples provide Services attribute , Can complete the original Startup class ConfigureServices Method ,Configure Some of the methods Use The operation is through app To complete .
builder.Services.AddMemoryCache();app.UseStaticFiles();if (app.Environment.IsDevelopment()){ app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", $"{builder.Environment.ApplicationName} v1"));}Map
builder.Build() Back to app Examples provide Map、Methods、MapXXX Method realization HttpMethod Mapping of routes . It's just Get Request as an example .Map and MapMethods Methods provide different features and parameters that can replace MapGet Method .
app.MapGet("/", () => "Hello World!");app.Map("/", [HttpGet] () => "Hello World!");HttpGet The attribute limit request is Get request , If not specified, the request method is not restricted ,Get、Post You can request to change the routing address
app.MapMethods("/", new List<string>() { HttpMethod.Get.ToString() }, () => "Hello World!");Application
Modify the application configuration directly in the code , For example, modify the listening port
app.Urls.Add("http://localhost:3000");//app.Run();app.Run("http://localhost:4000");priority app.Run > app.Urls.Add > launchSettings
Dependency Injection
Minimal APIs Constructor Injection... Cannot be used in , But it can be injected and ignored by parameters FromServices characteristic .
app.MapGet("/info", (IWebHostEnvironment env) => new { Time = DateTimeOffset.UtcNow, env.EnvironmentName});Context
some Http The context information of the request can also be specified directly through parameters , Methods direct use in vivo , Instead of MVC Medium Request etc. . Such as :
- HttpContext
- HttpRequest
- HttpResponse
- ClaimsPrincipal
- CancellationToken
app.MapGet("/context", (HttpContext httpContext) => new{ Data = httpContext.Connection.Id});More type references :github
Responses
Through static classes Results Returns the corresponding type of the standard , The implementation and ControllerBase Provide the same effect as the corresponding method .
app.MapGet("/ok/{id}", (int id) =>{ return Results.Ok($"ok:{id}");});Link Generation
By extending the method WithXXX You can configure the route , Such as through WithName Specify a name , Re pass LinkGenerator Production corresponds to Uri, 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)}");except WithXXX Wait for a few columns RoutingEndpointConvention Beyond the extension method , It also provides AuthorizationEndpointConvention Related extension methods RequireAuthorization、AllowAnonymous Instead of MVC Related features in the pattern ( Features can also be used, but there is an additional support method ).
This article only lists Minimal APIs Some simple uses of , Integrate Swagger And so on :https://minimal-apis.github.io/hello-minimal/
The return status code and type of the interface can be through the extension method Produces explain , Such as :Produces<ResponseMode>(contentType:"application/xml"); , however Interface remarks It doesn't seem to support , I tried a lot of ways, but I couldn't show it correctly .
Code Format
Minimal APIs The problem with the above example is Program There will be too much coding in the file , The mapping and response of all routes are together , Although the response method can be extracted by using the static method as follows , But all Route Map Still listed together , Can not be like Controller Same separation .
var handler = new HelloHandler();app.MapGet("/", handler.Hello);class HelloHandler{ public string Hello() { return "Hello World"; }}With the help of open source framework MASA.Contrib Provided MASA.Contrib.Service.MinimalAPIs Complete code encapsulation .
Detailed usage reference MASA.EShop
Program.cs
var builder = WebApplication.CreateBuilder(args);var app = builder.Services.AddServices(builder);app.Run();HelloService.cs
public class HelloService : ServiceBase{ public HelloService(IServiceCollection services): base(services) => App.MapGet("/api/v1/helloworld", ()=>"Hello World"));}We are acting , New framework 、 New ecology
Our goal is The freedom of the 、 Easy-to-use 、 Highly malleable 、 functional 、 Robust .
So we learn from Building blocks Design concept of , Working on a new framework MASA Framework, What are its characteristics ?
- Native support Dapr, And allow Dapr Replace with traditional means of communication
- Unlimited architecture , Single application 、SOA、 Micro services support
- Support .Net Native framework , Reduce the burden of learning , In addition to the concepts that must be introduced in a specific field , Insist on not making new wheels
- Rich ecological support , In addition to the framework, there are component libraries 、 Authority Center 、 Configuration center 、 Troubleshooting center 、 A series of products such as Alarm Center
- Unit test coverage of the core code base 90%+
- Open source 、 free 、 Community driven
- What is the ? We are waiting for you , Come together and discuss
After several months of production project practice , Completed POC, At present, the previous accumulation is being refactored into new open source projects
At present, the source code has been synchronized to Github( The document site is under planning , Will gradually improve ):
QQ Group :7424099
Wechat group : Plus technology operation wechat (MasaStackTechOps), Remarks , Invite in

------ END ------
Author's brief introduction
Ma Yue :MASA Technical team members .
边栏推荐
- 108. simple chat room 11: realize client group chat
- Convert the decimal positive integer m into the number in the forward K (2 < =k < =9) system and output it in bits
- Call the random function to generate 20 different integers and put them in the index group of institute a
- Niuke programming problem -- dynamic programming of must brush 101 (a thorough understanding of dynamic programming)
- 【小5聊】毕业8年,一直在追梦的路上
- JUnit unit test
- Science | 红树林中发现的巨型细菌挑战传统无核膜观念
- 《软件工程》期末重点复习笔记
- Stm32h7b0 replaces the h750 program, causing the MCU to hang up and unable to burn the program
- [Error] ld returned 1 exit status
猜你喜欢

Structure the graduation project of actual combat camp

1-12vmware adds SSH function

Kubecon China 2021 Alibaba cloud special session is coming! These first day highlights should not be missed

建立自己的网站(16)

心情不好,我就这样写代码

Constructors and Destructors

Teach you to learn dapr - 5 Status management

When a programmer is disturbed 10 times a day, the consequences are amazing!

无需人工先验!港大&同济&LunarAI&旷视提出基于语义分组的自监督视觉表征学习,显著提升目标检测、实例分割和语义分割任务!...

用Attention和微调BERT进行自然语言推断-PyTorch
随机推荐
Greenplum database fault analysis - semop (id=2000421076, num=11) failed: invalid argument
Calculate the average of N numbers in the group indexed by the formal parameter x, move the data less than the average in the group indexed to the front of the array, and move the data greater than or
TCP congestion control details | 1 summary
[from database deletion to running] JDBC conclusion (finish the series in one day!! run as soon as you finish learning!)
【小5聊】毕业8年,一直在追梦的路上
JS tutorial using electron JS build native desktop application ping pong game
Gui+sqlserver examination system
并发编程整体脉络
Leetcode 1170. 比较字符串最小字母出现频次(可以,已解决)
心情不好,我就这样写代码
对话长安马自达高层,全新产品将在Q4发布,空间与智能领跑日系
Least squares system identification class II: recursive least squares
Swap two numbers
Web3去中心化存储生态图景
STM32F103C8T6实现呼吸灯代码
架构实战营毕业设计
When a programmer is disturbed 10 times a day, the consequences are amazing!
JUnit unit test
Develop operator based on kubebuilder (for getting started)
What is flush software? Is it safe to open an account online?