[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>
posted @ 2024-02-02 11:25  trykle  阅读(32)  评论(0编辑  收藏  举报