DotNet 8 Minimal API with AOT (二): 编写接口

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

书接上回 DotNet 8 Minimal API with AOT: Part 1

这是使用 DotNet 8 Minimal API with AOT 系列的第二部分,开始实行一个 API 接口。

一个最简单的 API 接口

app.MapGet("/hello", () => "Hello World!");

测试一下:

> curl http://localhost:5141/hello
Hello World!¶

get 请求就是 MapGet; post 请求就是 MapPost。

独立的处理函数

我还是觉得上面那种 lambda 的写法非常别扭,所以试试 handler method 的写法:

app.MapGet("/hello2", HelloHandler);

string HelloHandler()
{
    return "Hello world2!";
}

测试一下:

> curl http://localhost:5141/hello2
Hello world2!¶

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

参考:

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

在安装有 DotNet 8 SDK 环境的 Ubuntu WSL 中测试。

app.MapGet("/run", BashCommandHandler);
app.MapGet("/run2", BashCommand2Handler);

// 立即返回
string BashCommandHandler() {
    Process.Start("touch", "/tmp/ok.md");
    Process.Start("sleep", "3");
    return "ok";
}

// 等待执行完返回
async Task<string> BashCommand2Handler() {
    await Process.Start("sleep", "3").WaitForExitAsync();
    return "ok";
}

对比这两种不同方式的响应速度:

> time curl http://localhost:5141/run
ok
________________________________________________________
Executed in   35.01 millis    fish           external
   usr time    0.00 micros    0.00 micros    0.00 micros
   sys time    0.00 micros    0.00 micros    0.00 micros

> time curl http://localhost:5141/run2
ok
________________________________________________________
Executed in    3.04 secs   fish           external
   usr time   15.62 millis    0.00 micros   15.62 millis
   sys time    0.00 millis    0.00 micros    0.00 millis

会看到:

  • 不使用异步 await 的形式,立即返回了
  • 使用了异步 await 的形式,等待执行完,才返回 ok

注意:async 标注的函数,需要使用 Task 类型,否则会在编译时报错。

error CS1983: The return type of an async method must be void, Task, Task, a task-like type, IAsyncEnumerable, or IAsyncEnumerator

至此,API 部分已完成,下面就是在 html 中通过 js 调用后台 API 接口了。

其他

还没搞明白怎么在 AOT 模式下返回一个 JSON。

继续阅读 📚

微信关注我哦 👍

大象工具微信公众号

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

tags: dotnet