.Net Minimal API 介绍
Minimal APIs 是.Net 6 中新增的模板,借助 C# 10 的一些特性以最少的代码运行一个 Web 服务。本文脱离 VS 通过 VS Code,完成一个简单的 Minimal Api 项目的开发。
创建项目
新建一个文件夹,用来管理我们的项目文件,文件夹内启动命令行,通过dotnet new web
创建项目。
1 | Minimal |
运行项目
项目目录下执行dotnet run
,运行项目。
1 | PS C:\Users\User01\Desktop\Minimal> dotnet run |
运行效果如下:
Coding
builder 实例提供了 Services 属性,可以完成原本 Startup 类 ConfigureServices 方法中注册服务的工作,Configure 方法的一些 Use 操作则通过 app 来完成。
1 | builder.Services.AddMemoryCache(); |
Map
builder.Build()返回的 app 实例提供了 Map、Methods、MapXXX 方法实现 HttpMethod 路由的映射。
这里只以 Get 请求为例。Map 和 MapMethods 方法提供不同的特性和参数可以代替 MapGet 方法。
1 | app.MapGet("/", () => "Hello World!"); |
1 | app.Map("/", [HttpGet] () => "Hello World!"); |
HttpGet 特性限定请求为 Get 请求,如果不指定则不限制请求方法,Get、Post 等方式可以请求改路由地址
1 | app.MapMethods("/", new List<string>() { HttpMethod.Get.ToString() }, () => "Hello World!"); |
Application
代码内直接修改应用程序配置,如修改监听端口
1 | app.Urls.Add("http://localhost:3000"); |
优先级 app.Run > app.Urls.Add > launchSettings
Dependency Injection
Minimal APIs 中无法使用构造函数注入,但可以通过参数方式注入并忽略 FromServices 特性。
1 | app.MapGet("/info", (IWebHostEnvironment env) => new { |
Context
一些 Http 请求的上下文信息也可以通过参数直接指定,方法体内直接使用,代替 MVC 中的 Request 等。如:
- HttpContext
- HttpRequest
- HttpResponse
- ClaimsPrincipal
- CancellationToken
1 | app.MapGet("/context", (HttpContext httpContext) => new |
更多类型参考:github
Responses
通过静态类 Results 返回标准的相应类型,实现和 ControllerBase 提供对应方法相同的效果。
1 | app.MapGet("/ok/{id}", (int id) => |
Link Generation
通过扩展方法 WithXXX 等可以对路由进行一些配置,如通过 WithName 指定名称,再通过 LinkGenerator 生产对应 Uri,避免硬编码
1 | app.MapGet("/context", (HttpContext httpContext) => new |
除了 WithXXX 等一些列 RoutingEndpointConvention 扩展方法外,还提供了 AuthorizationEndpointConvention 相关扩展方法 RequireAuthorization、AllowAnonymous 代替 MVC 模式中的相关特性(特性也还可以用只是多了一个支持方式)。
本文只列出 Minimal APIs 的一些简单用法,集成 Swagger 等用法内容参考:https://minimal-apis.github.io/hello-minimal/
接口的返回状态码和类型等可以通过扩展方法 Produces 说明,如:Produces
(contentType:”application/xml”); ,但是接口备注貌似还不支持,我尝试了很多方式都不能正确显示。
Code Format
Minimal APIs 上面示例存在的问题是 Program 文件中会有太多的编码,所有路由的映射和响应都在一起,虽然可以通过如下方式使用静态方法抽离响应方法,但所有的 Route Map 还是列在一起,不能像 Controller 一样分离。
1 | var handler = new HelloHandler(); |
可以借助开源框架 MASA.Contrib提供的 MASA.Contrib.Service.MinimalAPIs 完成代码封装。
详细用法参考 MASA.EShop
Program.cs
1 | var builder = WebApplication.CreateBuilder(args); |
HelloService.cs
1 | public class HelloService : ServiceBase |
.Net Minimal API 介绍
https://blogs.masastack.com/2021/11/06/independent/minimal-api/minimal-api/