Menu
CoddyTech

Sayfalama

Coddy'nin ASP.NET Core Journey'sinin REST API'leri bölümünün bir parçası. Ders 13 / 20.

10.000 sipariş içeren bir sipariş API'si hepsini aynı anda yanıtlayamaz. Sayfalama tek bir bölümü yanıtlar: GET /api/orders?page=3&pageSize=20, 41 ile 60 arasındaki siparişleri getirir. İstemcinin ayrıca “500 sayfadan 3. sayfa” gösterebilmek için toplam sayıya ihtiyacı vardır ve bir başlık bunu gövdenin yapısını değiştirmeden taşır.

app.MapGet("/api/orders", (HttpResponse response, int page = 1, int pageSize = 20) =>
{
    var matching = orders.ToList();
    response.Headers["X-Total-Count"] = matching.Count.ToString();
    return Results.Ok(matching.Skip((page - 1) * pageSize).Take(pageSize));
});

Varsayılan bir değer, sorgu parametresini isteğe bağlı hâle getirir. Bir HttpResponse parametresi, oluşturulmakta olan yanıttır; bu nedenle yanıtı döndürmeden önce bir başlık ayarlayabilirsin. X-Total-Count, sayfalamadan önce filtrelerle eşleşen siparişleri sayar. 1'in altındaki sayfaları reddet ve sayfa boyutunu sınırla; böylece hiçbir istemci hepsini aynı anda isteyemez.

challenge icon

Görev

Orta

Görevleri her seferinde bir sayfa olacak şekilde yanıtla ve toplamda kaç görev olduğunu belirt.

  1. GET /api/tasks lambda'sına, sort parametresinden sonra üç parametre ekle: HttpResponse response, int page = 1 ve int pageSize = 10.
  2. Hatalar sözlüğüne, page değeri 1'in altındaysa page altında Page starts at 1. hatasını; pageSize değeri 1 ile 50 aralığının dışındaysa pageSize altında Page size is 1 to 50. hatasını ekle.
  3. Filtreleme ve sıralama işleminden sonra sonucu bir listeye dönüştür. X-Total-Count başlığını bu listenin eleman sayısına ayarla, ardından yalnızca ilgili sayfayı yanıtla: (page - 1) * pageSize görevi atla ve pageSize kadar görev al.

GET /api/tasks?page=2&pageSize=2 yalnızca 3. görevi yanıtlar ve X-Total-Count: 3 değerini döndürür. Son sayfayı aşan bir sayfa isteği 200 ve [] yanıtını verir.

Deneyin: Çalıştır'a bas ve GET /api/tasks?page=2&pageSize=2 isteğini gönder: 3. görev yanıtlanır ve Headers sekmesinde X-Total-Count: 3 görünür. GET /api/tasks?done=false&pageSize=1 isteğini gönder: 1. görev ve X-Total-Count: 2 yanıtlanır. GET /api/tasks?page=0&pageSize=99 isteğini gönder: her iki hatayla birlikte 400 yanıtı alırsın.

Kendin dene

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, string? sort) =>
{
    var errors = new Dictionary<string, string[]>();
    if (sort is not null && sort != "id" && sort != "title")
        errors["sort"] = ["Sort by id or title."];
    if (errors.Count > 0) return Results.ValidationProblem(errors);

    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));
    if (sort == "title") result = result.OrderBy(t => t.Title);
    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);
quiz iconKendini test et

Bu ders kısa bir quiz içerir. Soruları yanıtlamak ve ilerlemeni kaydetmek için derse başla.

REST API'leri bölümündeki tüm dersler