agilelabs-fx-docs main tutorials/backend-init/configure-webapi.md

接入 WebAPI 基础能力

本页负责把后端宿主推进到“可以暴露最小 API”的状态,并让返回结构与现有前端契约保持一致。后续前端联调和认证都建立在这里的控制器骨架上。

这篇教程解决什么

  • 控制器和路由应该从哪里接入。
  • 最小 API 如何返回统一的前端契约结构。
  • 后续前端联调应该先依赖哪个接口。

前置条件

配套代码

我们要做的事

  • 新增最小控制器。
  • 暴露一个公开接口供前端和自测使用。
  • 使用 { data, code, msg, errMsg, tid } 这组字段作为最小返回包。

操作步骤

  1. src/BackendStarter.Api/Controllers 下新增 DemoController.cs
[ApiController]
[Route("api/demo")]
public sealed class DemoController(IWeatherQueryRepository weatherQueryRepository) : ControllerBase
{
    [HttpGet("hello")]
    public IActionResult GetHello()
    {
        var snapshot = weatherQueryRepository.GetToday();

        return Ok(new
        {
            data = new
            {
                message = "backend-starter is running.",
                snapshot.City,
                snapshot.TemperatureC,
                snapshot.Condition,
                generatedAt = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
            },
            code = 200,
            msg = (string?)null,
            errMsg = (string?)null,
            tid = HttpContext.TraceIdentifier
        });
    }
}
  1. 确认宿主里已经启用了控制器映射:
builder.Services.AddControllers();
app.MapControllers();
  1. 启动项目后调用最小公开接口:
curl http://localhost:5000/api/demo/hello

如果你的本地端口不是 5000,用启动日志里的实际地址替换。

验证结果

  • /api/demo/hello 可以访问。
  • 返回 JSON 中已经包含 datacodemsgerrMsgtid 这些字段。
  • 前端后续可以直接把这个接口作为最小联调入口。

下一篇读什么