DotNet 8 Minimal API with AOT (一): 新建项目

更新日期: 2024-07-20 阅读次数: 603 字数: 800 分类: Windows

我想用 DotNet 8 的 Minimal API 实现一个简单的服务器操作界面, 点击页面中的一个按钮,自动执行 Linux 服务器中的一行命令。(为何不用 PHP 或是 golang 去实现,因为我想换个口味)

初步构想是:

  • api 提供接口
  • html 放 wwwroot 目录下
  • 尝试一下 AOT 版本的 Minimal API 部署方式

为何选择 Native AOT

虽然有几种不同方式可以部署 ASP.NET 8 Minimal API 服务,但是我部署想试试 AOT。

Native AOT is a deployment model that uses an ahead-of-time compiler to compile IL to native code at the time of publish. Native AOT apps have faster startup time, smaller memory footprints, and can run on machines that don’t have the .NET runtime installed.

简而言之,就是跟 golang 完全相同的部署体验。当然 .Net 8 的交叉编译还是不及 golang

使用 Native AOT 的可行性

参考:

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/native-aot?view=aspnetcore-8.0

StaticFiles 是支持 AOT 的,但是 minimal API 只是部分支持。(json 序列化似乎需要特殊配置)

然后,找了篇文章看,应该是没问题的。所以,开干吧。

新建 Minimal API 项目 with AOT

webapiaot 是一个标准项目模板

dotnet new webapiaot -o NetServerTool

执行成功,会看到输出:

The template "ASP.NET Core Web API (native AOT)" was created successfully.

运行,看看效果

> dotnet.exe run

Building...
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://localhost:5141
info: Microsoft.Hosting.Lifetime[0]
      Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
      Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
      Content root path: D:\work\NetServerTool

如果在浏览器,直接访问 http://localhost:5141 会报 404 错误。

因为,这个项目模板,是实现了一个 todo 的小 demo,真正的 api URL 是:

http://localhost:5141/todos

然后就可以看到一段 JSON 返回。说明,服务运行成功。

模板的概要代码

代码里的核心逻辑,就这么几行:

var todosApi = app.MapGroup("/todos");
todosApi.MapGet("/", () => sampleTodos);
todosApi.MapGet("/{id}", (int id) =>
    sampleTodos.FirstOrDefault(a => a.Id == id) is { } todo
        ? Results.Ok(todo)
        : Results.NotFound());

app.Run();

xxx.csproj:

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <InvariantGlobalization>true</InvariantGlobalization>
    <PublishAot>true</PublishAot>
  </PropertyGroup>

</Project>

开始修改吧。

添加一个网页

修改 Program.cs:

var app = builder.Build();
app.UseStaticFiles();  // 新增配置,使我们能访问 wwwroot 目录下的静态文件

然后新建一个 wwwroot 目录,其下面新建一个 index.html 文件,随便写个 hello world 即可。

注:wwwroot 在此 AOT 模板下默认不存在,如果不手动创建,会收到警告信息一条:

> dotnet.exe run
Building...
warn: Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware[16]
      The WebRootPath was not found: D:\work\NetServerTool\wwwroot. Static files may be unavailable.

再次,运行 dotnet run, 并在浏览器里访问

http://localhost:5141/index.html

即可看到刚才新建的网页内容了。然后就是写个 api 接口,然后执行系统命令啦。

参考:

https://learn.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-8.0

实现一个能执行 linux 命令的 API

参考:

https://www.reddit.com/r/csharp/comments/kg6us8/is_there_is_a_way_to_execute_bash_commands_from_c/

太困了,今天就写到这儿吧,提交代码,睡觉!明天继续。

生成 gitignore 文件

> dotnet.exe new gitignore
The template "dotnet gitignore file" was created successfully.

继续阅读 📚

参考

  • https://anuraj.dev/blog/how-to-use-native-aot-to-improve-performance-of-aspnetcore-apps
  • https://learn.microsoft.com/en-us/aspnet/core/fundamentals/aot/native-aot-tutorial?view=aspnetcore-8.0&tabs=net-cli
  • 视频 https://learn.microsoft.com/en-us/shows/dotnetconf-2023/tiny-fast-aspnet-core-apis-with-native-aot

微信关注我哦 👍

大象工具微信公众号

我是来自山东烟台的一名开发者,有敢兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式

tags: dotnet