01-hello-world-minimal-api

知识库
知识库文档
/tech-stacks/csharp/examples/01-hello-world-minimal-api.md

文档

C# Hello World — ASP.NET Core Minimal API

目标

用 C# 的 ASP.NET Core Minimal API 创建一个 Web 服务,访问根路径返回 JSON 格式的 "Hello World"。

完整代码

// Program.cs
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

// 根路由 — Hello World
app.MapGet("/", () => Results.Ok(new
{
    message = "Hello World",
    timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds()
}));

// 健康检查
app.MapGet("/health", () => Results.Ok(new { status = "ok" }));

app.Run();

运行步骤

# 1. 创建项目
dotnet new web -n HelloApi
cd HelloApi

# 2. 将上述代码替换 Program.cs

# 3. 运行
dotnet run

测试

curl http://localhost:5000/
# 输出: {"message":"Hello World","timestamp":1717000000}

curl http://localhost:5000/health
# 输出: {"status":"ok"}

预期输出

$ dotnet run
Building...
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: http://localhost:5000

要点说明

  • WebApplication.CreateBuilder() 创建应用构建器(自动加载配置、DI 容器、日志)
  • MapGet("/", ...) 定义 GET 路由,Lambda 作为处理器
  • Results.Ok() 返回 HTTP 200 + JSON 自动序列化
  • Minimal API 无需 Controller 类,适合微服务和小型 API

信息

路径
/tech-stacks/csharp/examples/01-hello-world-minimal-api.md
更新时间
2026/5/30