Menu
CoddyTech

Xung đột

Thuộc phần REST API trong hành trình ASP.NET Core của Coddy. Bài học 9 trên 20.

Một người dùng thứ hai có tên "Ada" khiến thông tin đăng nhập trở nên không rõ ràng, dù phần thân yêu cầu hợp lệ. Đó là 409 Conflict: yêu cầu xung đột với dữ liệu đã được lưu. Mã 400 có nghĩa là bản thân phần thân yêu cầu không hợp lệ; mã 409 có nghĩa là phần thân hợp lệ nhưng hiện không thể áp dụng.

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);

Mọi người đọc "Ada" và "ada" là cùng một tên, vì vậy hãy so sánh bằng StringComparison.OrdinalIgnoreCase. Khi yêu cầu đổi tên người dùng, hãy loại người dùng đó khỏi tìm kiếm, nếu không, lưu biểu mẫu mà không đổi tên sẽ tạo xung đột với chính nó. Results.Problem trả lời theo định dạng chi tiết vấn đề, kèm tiêu đề và trạng thái của bạn.

challenge icon

Thử thách

Trung bình

Hai tác vụ cùng tên "Send the invoice" khiến danh sách khó theo dõi. Hãy từ chối tiêu đề đã được một tác vụ khác sử dụng.

  1. Trong Program.cs, bên dưới nextId, viết một hàm cục bộ bool TitleTaken(string title, int exceptId): trả về true khi một tác vụ không phải exceptId có tiêu đề đó, không phân biệt chữ hoa chữ thường.
  2. Trong POST, sau bước kiểm tra xác thực, trả về Results.Problem(title: "A task with this title already exists.", statusCode: 409) nếu tiêu đề đã được sử dụng, và không thêm gì cả. POST không có tác vụ nào cần loại trừ, vì vậy hãy truyền 0.
  3. Làm tương tự trong PUT, truyền id của tác vụ để tác vụ có thể giữ nguyên tiêu đề của mình hoặc thay đổi chữ hoa chữ thường.
  4. Trong PATCH, chỉ kiểm tra khi nội dung gửi lên có tiêu đề (patch.Title khác null).

Yêu cầu bị từ chối không làm thay đổi gì. Nội dung phản hồi 409 là:

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

Thử nhé: nhấn Chạy rồi gửi POST { "title": "book the MEETING room" } đến /api/tasks: 409, vì tác vụ 2 có tiêu đề đó. Gửi PUT { "title": "Book the Meeting Room", "done": false } đến /api/tasks/2: 200, vì đây là tiêu đề của chính tác vụ đó. Gửi PATCH đến /api/tasks/3 với { "title": "Write the project brief" }: 409. Gửi POST { "title": "Order new chairs" }: 201 với id 4.

Tự làm thử

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);

Tất cả bài học trong REST API