Lesson 6 of 8
Pagination, Filtering & Sorting
Every production API needs pagination. Offset pagination is simple but slow for large datasets (OFFSET 10000 scans 10,000 rows). Cursor pagination uses a stable cursor (last seen ID or created_at) - O(log n) performance regardless of page depth.
Cursor Pagination & OData Filtering
// ━━ Cursor-based pagination ━━
// Client: GET /api/products?limit=20&cursor=eyJpZCI6IjEyMyJ9
// Server: SELECT * FROM Products WHERE Id > cursor_id ORDER BY Id LIMIT 20
public record CursorPage<T>(
List<T> Items,
string? NextCursor, // opaque cursor for next page (base64 encoded)
bool HasNextPage,
int Limit);
[HttpGet]
public async Task<ActionResult<CursorPage<ProductDto>>> GetProducts(
[FromQuery] int limit = 20,
[FromQuery] string? cursor = null, // opaque cursor from previous response
[FromQuery] string? category = null,
[FromQuery] string? search = null,
[FromQuery] string sort = "created_at_desc",
CancellationToken ct = default)
{
var (sortField, sortDir) = sort switch
{
"name_asc" => ("Name", "ASC"),
"name_desc" => ("Name", "DESC"),
"price_asc" => ("Price", "ASC"),
"price_desc" => ("Price", "DESC"),
"created_at_desc" => ("CreatedAt", "DESC"),
_ => ("CreatedAt", "DESC")
};
// Decode cursor (base64 JSON: {"id":"...", "value":"..."})
Guid? afterId = null;
if (cursor is not null)
{
var decoded = System.Text.Json.JsonSerializer.Deserialize<CursorPayload>(
Convert.FromBase64String(cursor));
afterId = decoded?.Id;
}
var query = dbContext.Products.AsNoTracking()
.Where(p => p.IsActive)
.Where(p => category == null || p.CategorySlug == category)
.Where(p => search == null || p.Name.Contains(search) || p.Description!.Contains(search))
.Where(p => afterId == null || p.Id.CompareTo(afterId) > 0); // cursor filter
var items = await query
.OrderByDescending(p => p.CreatedAt)
.Take(limit + 1) // take one extra to check if next page exists
.Select(p => new ProductDto(p.Id, p.Name, p.Price, p.CategorySlug, p.CreatedAt))
.ToListAsync(ct);
var hasNext = items.Count > limit;
if (hasNext) items.RemoveAt(items.Count - 1);
// Encode next cursor
string? nextCursor = null;
if (hasNext && items.Count > 0)
{
var last = items.Last();
nextCursor = Convert.ToBase64String(
System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(
new CursorPayload(last.Id, last.CreatedAt.Ticks.ToString())));
}
return Ok(new CursorPage<ProductDto>(items, nextCursor, hasNext, limit));
}
record CursorPayload(Guid Id, string Value);
record ProductDto(Guid Id, string Name, decimal Price, string Category, DateTime CreatedAt);
class AppDbContext2
{
public IQueryable<ProductEntity> Products => null!;
}
class ProductEntity { public Guid Id { get; set; } public string Name { get; set; } = ""; public decimal Price { get; set; } public string CategorySlug { get; set; } = ""; public string? Description { get; set; } public bool IsActive { get; set; } public DateTime CreatedAt { get; set; } }
AppDbContext2 dbContext = null!;Tip
Tip
Practice Pagination Filtering Sorting in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Pagination, Filtering & Sorting
Practice Task
Note
Practice Task - (1) Write a working example of Pagination Filtering Sorting from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with Pagination Filtering Sorting is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.
Finished this lesson?