Menu
CoddyTech

使用 PATCH 部分更新

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

PATCH 只会修改请求正文中发送的字段。要区分未提供的字段和已设置的字段,请将补丁记录的每个属性都设为可空:缺失的字段会绑定为 null。

record ProfilePatch(string? Name, string? City);

profiles[index] = profile with
{
    Name = patch.Name ?? profile.Name,
    City = patch.City ?? profile.City,
};

with 会复制一条记录,并修改你列出的属性。?? 会在补丁中的值为 null 时保留旧值。bool? 的工作方式也一样:false 是客户端发送的值,而 null 表示客户端没有发送任何内容。因此,{ "city": "Lyon" } 会更改个人资料中的城市,同时保留姓名。

challenge icon

挑战

简单

让客户端只修改任务的一个字段,例如勾选任务已完成,而不必再次发送标题。

  1. 在 Program.cs 的底部声明 record TaskPatch(string? Title, bool? Done);
  2. 映射 PATCH /api/tasks/{id:int},参数为 int id 和 TaskPatch patch。如果没有对应 id 的任务,就返回 Results.NotFound()。
  3. 否则,使用 with 创建任务副本并保存:每个属性都采用补丁中的值;如果补丁中的值为 null,则保留任务原来的值。使用 Results.Ok 返回修改后的任务。

使用 { "done": true } 请求 PATCH /api/tasks/1,会返回 200 和:

{ "id": 1, "title": "Write the project brief", "done": true }

试一试:按下“运行”,选择 PATCH,路径为 /api/tasks/1,请求正文为 { "done": true },然后按“发送”:返回上面的结果,标题保持不变。使用 { "title": "Book the big room" } 请求 PATCH /api/tasks/2:标题会更新,而 "done": true 保持不变。请求 PATCH /api/tasks/99 会返回 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.MapPut("/api/tasks/{id:int}", (int id, TaskInput input) =>
{
    var index = tasks.FindIndex(t => t.Id == id);
    if (index == -1) return Results.NotFound();
    tasks[index] = new TaskItem(id, input.Title, input.Done);
    return Results.Ok(tasks[index]);
});

app.Run();

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

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

REST API中的所有课