Menu
CoddyTech

资源与 URL

本课属于 Coddy ASP.NET Core 学习旅程的“REST API”单元。第 1 课,共 20 课。

其他程序会调用你的 API,因此它的 URL 应该容易猜到。大多数 Web API 都遵循一种叫作 REST 的风格:每个 URL 都指向一个资源,也就是 API 存储的内容;HTTP 方法则说明要对它执行什么操作。

GET    /api/invoices      the list of invoices
GET    /api/invoices/7    invoice 7
POST   /api/invoices      add an invoice
DELETE /api/invoices/7    remove invoice 7

路径中放名词,不放动词:如果使用 /api/getInvoice?id=7,每个客户端都必须为每种操作学习一个新词。集合使用复数名称,单个项目的路径则由集合路径加上它的 ID 组成。

app.MapGet("/api/invoices/{id:int}", (int id) =>
{
    var invoice = invoices.Find(i => i.Id == id);
    return invoice is null ? Results.NotFound() : Results.Ok(invoice);
});

{id:int} 是带有约束的路由参数:它只匹配整数,因此 /api/invoices/abc 不会匹配任何路由,响应为 404。如果 ID 没有对应的发票,也会通过 Results.NotFound() 返回 404。

challenge icon

挑战

简单

在本单元中,你将构建一个任务跟踪 API。它从三个任务和 GET /api/tasks 开始,该接口会返回所有任务。这些任务是 TaskItem 记录,因为 .NET 已经有一个名为 Task 的类型。接下来,为单个任务添加 URL。

  1. 在 Program.cs 中的 GET /api/tasks 下方,映射 GET /api/tasks/{id:int}。
  2. 使用 tasks.Find 查找 Id 等于 id 的任务,并使用 Results.Ok(task) 返回它。GET /api/tasks/2 会返回:
    { "id": 2, "title": "Book the meeting room", "done": true }
  3. 如果没有任务的 id 与该 id 匹配,就返回 Results.NotFound():状态码为 404,响应体为空。

试试看:点击“运行”。面板会发送 GET /api/tasks 并显示这三个任务。发送 GET /api/tasks/2:返回 200 和上面的任务。发送 GET /api/tasks/99:返回 404。发送 GET /api/tasks/abc:同样返回 404,因为 {id:int} 只匹配数字。

亲手试试

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

var tasks = new List<TaskItem>
{
    new(1, "Write the project brief", false),
    new(2, "Book the meeting room", true),
    new(3, "Send the invoice", false),
};

app.MapGet("/api/tasks", () => tasks);

app.Run();

record TaskItem(int Id, string Title, bool Done);
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

REST API中的所有课