ASP.NET Core Web API Interview Question #47

How should pagination parameters be validated?

DTOs, Model Binding, Validation & API Responses Junior Beginner

Quick Interview Answer

Set sensible defaults and enforce minimum and maximum values. Without a maximum page size, a client may accidentally or deliberately request an extremely large result set and create unnecessary database, memory, serialization, and network load.

Detailed Explanation

Set sensible defaults and enforce minimum and maximum values. Without a maximum page size, a client may accidentally or deliberately request an extremely large result set and create unnecessary database, memory, serialization, and network load.

The API should also use deterministic ordering so records do not move unpredictably between pages.

Code Example

page = Math.Max(page, 1);
pageSize = Math.Clamp(pageSize, 1, 100);

var items = await query
    .OrderBy(x => x.Id)
    .Skip((page - 1) * pageSize)
    .Take(pageSize)
    .ToListAsync(token);