Menu
CoddyTech

使用 PUT 替换

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

PUT 用于替换一个条目。请求体包含该条目的完整新状态,并发送到该条目自己的 URL。请求体中省略的字段会使用默认值。重复发送相同的 PUT 请求会得到相同的结果,因此 PUT 是幂等的:客户端超时后可以重试。POST 则不是,因为第二次 POST 会添加第二个条目。

app.MapPut("/api/products/{id:int}", (int id, ProductInput input) =>
{
    var index = products.FindIndex(p => p.Id == id);
    if (index == -1) return Results.NotFound();
    products[index] = new Product(id, input.Name, input.Price);
    return Results.Ok(products[index]);
});

id 来自路径,而不是请求体,因此客户端无法将产品移动到另一个 id。FindIndex 会返回该条目在列表中的位置;如果没有匹配项,则返回 -1。products[index] = ... 会将新版本存储在原位置。

challenge icon

挑战

简单

让客户端替换一个任务。

  1. 在 Program.cs 中,映射 PUT /api/tasks/{id:int},并添加 int id 和 TaskInput input 参数。请求体的结构与 POST 请求体相同。
  2. 使用 tasks.FindIndex 查找任务的位置。如果结果是 -1,就返回 Results.NotFound(),不添加任何内容。
  3. 否则,将 new TaskItem(id, input.Title, input.Done) 存储在该位置,并使用 Results.Ok 返回它。向 /api/tasks/1 发送 { "title": "Write the final brief", "done": true },会返回 200 和:
    { "id": 1, "title": "Write the final brief", "done": true }

试试看:按“运行”,选择 PUT,路径填写 /api/tasks/1,请求体填写上面的内容,然后点击“发送”:会返回 200 和上面的任务。发送 GET /api/tasks/1:查看新的标题。向 /api/tasks/2 发送 PUT 请求,请求体为 { "title": "Book the big room" }:任务 2 原本已完成,但请求体中没有 done,所以返回结果中会是 "done": false。向 /api/tasks/99 发送 PUT 请求会返回 404。

亲手试试

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),
};
var nextId = 4;

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

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

app.MapPost("/api/tasks", (TaskInput input) =>
{
    var task = new TaskItem(nextId++, input.Title, input.Done);
    tasks.Add(task);
    return Results.Created($"/api/tasks/{task.Id}", task);
});

app.Run();

record TaskItem(int Id, string Title, bool Done);
record TaskInput(string Title, bool Done);

REST API中的所有课