Menu
CoddyTech

Sắp xếp

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

Tham số sort (parameter) cho phép client chọn thứ tự: GET /api/products?sort=price. Chỉ chấp nhận những thứ tự bạn hỗ trợ và trả về 400 cho mọi giá trị khác, để lỗi gõ như sort=prise được báo thay vì bị bỏ qua.

var errors = new Dictionary<string, string[]>();
if (sort is not null && sort != "name" && sort != "price")
    errors["sort"] = ["Sort by name or price."];
if (errors.Count > 0) return Results.ValidationProblem(errors);

if (sort == "price") result = result.OrderBy(p => p.Price);

OrderBy trả về một dãy mới đã được sắp xếp và không thay đổi danh sách. products.Sort(...) sẽ sắp xếp lại chính danh sách đã lưu, vì vậy mọi phản hồi sau đó cũng sẽ có thứ tự mới. Gom các lỗi vào cùng một từ điển giúp bạn thông báo tất cả lỗi cùng lúc khi một yêu cầu có nhiều lỗi.

challenge icon

Thử thách

Dễ

Cho phép client sắp xếp các nhiệm vụ theo tiêu đề.

  1. Thêm tham số thứ ba, string? sort, cho lambda GET /api/tasks.
  2. Ở đầu lambda, thu thập lỗi vào một từ điển. Khi sort khác null, id hoặc title, thêm Sort by id or title. vào mục sort, rồi trả về Results.ValidationProblem(errors) nếu từ điển có lỗi.
  3. Sau các bộ lọc, khi sort là title, sắp xếp kết quả theo tiêu đề bằng OrderBy. Nếu không có sort hoặc sort=id, các nhiệm vụ vẫn giữ thứ tự theo id.

GET /api/tasks?sort=title trả về các nhiệm vụ 2, 3 và 1: Book, Send, Write.

Thử ngay: nhấn Chạy và gửi GET /api/tasks?sort=title: kết quả theo thứ tự trên. Gửi GET /api/tasks: kết quả trở lại thứ tự theo id. Gửi GET /api/tasks?sort=size: nhận 400 với "errors": { "sort": ["Sort by id or title."] }. Gửi GET /api/tasks?done=false&sort=title: nhận các nhiệm vụ 3 và 1.

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;

bool TitleTaken(string title, int exceptId) =>
    tasks.Any(t => t.Id != exceptId && string.Equals(t.Title, title, StringComparison.OrdinalIgnoreCase));

app.MapGet("/api/tasks", (bool? done, string? search) =>
{
    IEnumerable<TaskItem> result = tasks;
    if (done is not null) result = result.Where(t => t.Done == done);
    if (!string.IsNullOrWhiteSpace(search))
        result = result.Where(t => t.Title.Contains(search, StringComparison.OrdinalIgnoreCase));
    return Results.Ok(result);
});

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);
    if (TitleTaken(input.Title, 0))
        return Results.Problem(title: "A task with this title already exists.", statusCode: 409);
    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();
    if (TitleTaken(input.Title, id))
        return Results.Problem(title: "A task with this title already exists.", statusCode: 409);
    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();
    if (patch.Title is not null && TitleTaken(patch.Title, id))
        return Results.Problem(title: "A task with this title already exists.", statusCode: 409);
    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