[asp.net core] 将web api项目改造成 minimal APIs,并使用 native AOT 编译
我有一个web接口很适合改造成aot
- 对启动速度和运算性能有一定要求
- 接口简单,拿到数据处理后返回结果的模式
- 无数据库,无其他依赖
- 不使用json,原本使用xml,改造后甚至放弃了xml,使用自定义简单字符串格式返回
实际结果:
- aot编译后项目为15M,初次启动速度有一定提升
- 性能测试无明显变化
native AOT 介绍
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/native-aot?view=aspnetcore-8.0
改造入口
var builder = WebApplication.CreateSlimBuilder(args); builder.WebHost.UseUrls("http://localhost:10088"); var app = builder.Build(); var api = app.MapGroup("/api"); //get api.MapGet("/test", (HttpContext httpContext) => { return $"{DateTime.Now} {Random.Shared.Next()}"; }); // post url数据 api.MapPost("/getUser/{id}", (int id) => { return $"1传递的id是:{id}"; }); //post 表单数据 api.MapPost("/getUser2", (HttpContext httpContext) => { int.TryParse(httpContext.Request.Form["id"], out var id); return $"2传递的id是:{id}"; }); app.Run();
在项目配置中添加
<PublishAot>true</PublishAot>
如果引用的目标程序集使用了反射,可以添加全量保留
<ItemGroup> <TrimmerRootAssembly Include="TargetAssemblyName" /> </ItemGroup>
分类:
Asp.Net Core
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
2019-02-02 maxscript.api