当前位置:网站首页>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 .
边栏推荐
- Develop operator based on kubebuilder (for getting started)
- Hyperf框架使用阿里云OSS上传失败
- [graduation season] a word for graduates: the sky is high enough for birds to fly, and the sea is wide enough for fish to leap
- C语言 头哥习题答案截图
- Arduino UNO + DS1302简单获取时间并串口打印
- Redis 迁移(操作流程建议)
- [understanding of opportunity -31]: Guiguzi - Daoyu [x ī] Crisis is the coexistence of danger and opportunity
- Développer un opérateur basé sur kubebuilder (démarrer)
- 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
- Pybullet robot simulation environment construction 5 Robot pose visualization
猜你喜欢

Pybullet robot simulation environment construction 5 Robot pose visualization

NFT 交易市场社区所有化势不可挡

Teach you to learn dapr - 8 binding

No manual prior is required! HKU & Tongji & lunarai & Kuangshi proposed self supervised visual representation learning based on semantic grouping, which significantly improved the tasks of target dete

【MATLAB项目实战】基于卷积神经网络与双向长短时(CNN-LSTM)融合的锂离子电池剩余使用寿命预测

Science | 红树林中发现的巨型细菌挑战传统无核膜观念

1-12Vmware新增SSH功能

5G未平6G再启,中国引领无线通信,6G的最大优势在哪里?

Teach you to learn dapr - 5 Status management

R329 (maix-ii-a (M2A) data summary
随机推荐
C language -- legal identifier and integer
JS tutorial - printing stickers / labels using the electronjs desktop application
Greenplum数据库故障分析——semop(id=2000421076,num=11) failed: invalid argument
知道这几个命令让你掌握Shell自带工具
牛客编程题--必刷101之动态规划(一文彻底了解动态规划)
[Li Kou brush question] monotone stack: 84 The largest rectangle in the histogram
Codeforces Round #802 (Div. 2)
基於Kubebuilder開發Operator(入門使用)
Hyperf框架使用阿里云OSS上传失败
How can I get the stock account opening discount link? Is online account opening safe?
JUnit unit test
Niuke programming problem -- dynamic programming of must brush 101 (a thorough understanding of dynamic programming)
Failed to upload hyperf framework using alicloud OSS
并发编程整体脉络
5g is not flat and 6G is restarted. China leads wireless communication. What is the biggest advantage of 6G?
Arduino UNO + DS1302简单获取时间并串口打印
Set up your own website (16)
[Blue Bridge Cup training 100 questions] scratch distinguishing prime numbers and composite numbers Blue Bridge Cup scratch competition special prediction programming question intensive training simul
C language --- basic function realization of push box 01
无需人工先验!港大&同济&LunarAI&旷视提出基于语义分组的自监督视觉表征学习,显著提升目标检测、实例分割和语义分割任务!...