当前位置:网站首页>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 .
边栏推荐
- Kept to implement redis autofailover (redisha) 1
- 基于STM32+华为云IOT设计的云平台监控系统
- Experience in hierarchical debugging of boards and cards
- day10每日3题(2):统计最大组的数目
- Calculate the sum of the main diagonals of the array
- Hyperf框架使用阿里云OSS上传失败
- 安信证券排名第几位?开户安全吗?
- [understanding of opportunity -31]: Guiguzi - Daoyu [x ī] Crisis is the coexistence of danger and opportunity
- Leetcode 1170. 比较字符串最小字母出现频次(可以,已解决)
- Binary array command of redis
猜你喜欢

Pybullet robot simulation environment construction 5 Robot pose visualization

【毕业季】致毕业生的一句话:天高任鸟飞,海阔凭鱼跃

Screenshot of the answers to C language exercises
![[机缘参悟-31]:鬼谷子-抵巇[xī]篇-危机是危险与机会并存](/img/e8/9c5f1658a252c3c80503b5021917f6.jpg)
[机缘参悟-31]:鬼谷子-抵巇[xī]篇-危机是危险与机会并存

Dialogue with the senior management of Chang'an Mazda, new products will be released in Q4, and space and intelligence will lead the Japanese system

用Attention和微调BERT进行自然语言推断-PyTorch

Develop operator based on kubebuilder (for getting started)

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

基於Kubebuilder開發Operator(入門使用)
Scala 基礎 (二):變量和數據類型
随机推荐
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
Learn about common functional interfaces
108. simple chat room 11: realize client group chat
[from deleting the database to running] the end of MySQL Foundation (the first step is to run.)
国内首款开源 MySQL HTAP 数据库即将发布,三大看点提前告知
知道这几个命令让你掌握Shell自带工具
Convert the decimal positive integer m into the number in the forward K (2 < =k < =9) system and output it in bits
Redis 迁移(操作流程建议)
C语言 头哥习题答案截图
MS|谢黎炜组发现混合益生菌制剂及其代谢产物可缓解结肠炎
Kept to implement redis autofailover (redisha) 1
数字藏品与NFT到底有何区别
5G未平6G再启,中国引领无线通信,6G的最大优势在哪里?
100+数据科学面试问题和答案总结 - 基础知识和数据分析
JS tutorial electron JS is a good tool for designing powerful multi platform desktop applications
Codeforces Round #802 (Div. 2)
Acid of redis
Leetcode 1169. 查询无效交易(如果数据量不大,这种题还是得暴力枚举解决)
What is the preferential account opening policy of securities companies now? Is it safe to open an account online now?
Redis order sorting command