Paginación
Parte de la sección API REST del Journey de ASP.NET Core de Coddy. Lección 13 de 20.
Una API de pedidos con 10,000 pedidos no puede responder a todos a la vez. La paginación devuelve un fragmento: GET /api/orders?page=3&pageSize=20 corresponde a los pedidos del 41 al 60. El cliente también necesita el total para mostrar «página 3 de 500», y un encabezado lo transporta sin cambiar la estructura del cuerpo.
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));
});Un valor predeterminado hace que un parámetro de consulta sea opcional. Un parámetro HttpResponse es la respuesta que se está construyendo, así que puedes establecer un encabezado antes de devolverla. X-Total-Count cuenta los pedidos que coinciden con los filtros, antes de paginar. Rechaza las páginas inferiores a 1 y limita el tamaño de página para que ningún cliente pueda solicitarlo todo a la vez.
Desafío
IntermedioResponde las tareas de una página a la vez e indica cuántas hay en total.
- Añade tres parámetros a la lambda
GET /api/tasks, después desort:HttpResponse response,int page = 1yint pageSize = 10. - En el diccionario de errores, añade
Page starts at 1.bajopagecuandopagesea menor que 1, yPage size is 1 to 50.bajopageSizecuandopageSizeesté fuera del rango de 1 a 50. - Después de filtrar y ordenar, convierte el resultado en una lista. Establece el encabezado
X-Total-Countcon su cantidad y, luego, responde solo con la página: omite(page - 1) * pageSizetareas y tomapageSize.
GET /api/tasks?page=2&pageSize=2 responde solo con la tarea 3, con X-Total-Count: 3. Una página que supere el final responde con 200 y [].
Pruébalo: pulsa «Ejecutar» y envía GET /api/tasks?page=2&pageSize=2: tarea 3, y la pestaña Headers muestra X-Total-Count: 3. Envía GET /api/tasks?done=false&pageSize=1: tarea 1 y X-Total-Count: 2. Envía GET /api/tasks?page=0&pageSize=99: 400 con ambos errores.
Pruébalo tú mismo
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);
Esta lección incluye un breve cuestionario. Empieza la lección para responderlo y registrar tu progreso.
Todas las lecciones de API REST
2Validación y errores
Rechazar entradas no válidas5Navegadores y alojamiento
CORS