Menu
CoddyTech

冲突

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

第二个名为“Ada”的用户会导致登录名无法区分,但请求正文是有效的。这就是 409 Conflict:请求与已存储的内容冲突。400 表示请求正文本身有误;409 表示请求正文没有问题,但当前无法应用。

bool NameTaken(string name, int exceptId) =>
    users.Any(u => u.Id != exceptId &&
        string.Equals(u.Name, name, StringComparison.OrdinalIgnoreCase));

if (NameTaken(input.Name, id))
    return Results.Problem(title: "That name is taken.", statusCode: 409);

人们会把“Ada”和“ada”看作同一个名字,所以要使用 StringComparison.OrdinalIgnoreCase 进行比较。重命名用户时,要将该用户排除在搜索范围之外,否则,保存一个名字未更改的表单时,就会与用户自身冲突。Results.Problem 会按照问题详情格式返回响应,其中包含你设置的标题和状态码。

challenge icon

挑战

中等

两个都叫 "Send the invoice" 的任务会让列表变得混乱。拒绝使用其他任务已有的标题。

  1. 在 Program.cs 中的 nextId 下方,编写一个本地函数 bool TitleTaken(string title, int exceptId):如果存在标题相同且不是 exceptId 的任务,则返回 true,忽略大小写。
  2. 在 POST 中,验证检查之后,如果标题已被占用,则返回 Results.Problem(title: "A task with this title already exists.", statusCode: 409),并且不添加任何内容。POST 没有要排除的任务,因此传入 0。
  3. 在 PUT 中执行相同的检查,传入任务的 id,这样任务可以保留自己的标题,也可以更改标题中的大小写。
  4. 在 PATCH 中,仅当请求正文发送了标题时才进行检查(patch.Title 不为 null)。

被拒绝的请求不会更改任何内容。409 响应正文如下:

{ "type": "https://tools.ietf.org/html/rfc9110#section-15.5.10", "title": "A task with this title already exists.", "status": 409, "traceId": "..." }

试一试:按“运行”,向 /api/tasks 发送 POST 请求,内容为 { "title": "book the MEETING room" }:返回 409,因为任务 2 已有这个标题。向 /api/tasks/2 发送 PUT 请求,内容为 { "title": "Book the Meeting Room", "done": false }:返回 200,因为这是该任务自己的标题。向 /api/tasks/3 发送 PATCH 请求,内容为 { "title": "Write the project brief" }:返回 409。发送 POST 请求,内容为 { "title": "Order new chairs" }:返回 201,id 为 4。

亲手试试

using System.ComponentModel.DataAnnotations;

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

app.UseExceptionHandler();
app.UseStatusCodePages();

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 errors = Validation.Errors(input);
    if (errors is not null) return Results.ValidationProblem(errors);
    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 errors = Validation.Errors(input);
    if (errors is not null) return Results.ValidationProblem(errors);
    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.MapPatch("/api/tasks/{id:int}", (int id, TaskPatch patch) =>
{
    var index = tasks.FindIndex(t => t.Id == id);
    if (index == -1) return Results.NotFound();
    var task = tasks[index];
    tasks[index] = task with
    {
        Title = patch.Title ?? task.Title,
        Done = patch.Done ?? task.Done,
    };
    return Results.Ok(tasks[index]);
});

app.MapDelete("/api/tasks/{id:int}", (int id) =>
{
    var removed = tasks.RemoveAll(t => t.Id == id);
    return removed == 0 ? Results.NotFound() : Results.NoContent();
});

app.Run();

record TaskItem(int Id, string Title, bool Done);
record TaskInput(
    [property: Required(ErrorMessage = "Title is required."), StringLength(80)] string Title,
    bool Done);
record TaskPatch(string? Title, bool? Done);

REST API中的所有课