Introduction
When building real-world applications using ASP.NET Core Web API, handling large amounts of data efficiently becomes very important. Imagine loading thousands of records in a single API response — it slows down performance, increases memory usage, and creates a poor user experience.
This is where Pagination in ASP.NET Core Web API comes into play.
Pagination helps you divide large datasets into smaller, manageable chunks (pages), making your API faster, scalable, and user-friendly.
What is Pagination?
Pagination is a technique used to split large data into smaller parts (pages).
Instead of returning all records at once, the API returns only a subset of data based on:
Page Number
Page Size
👉 Example:
If you have 1000 products:
Page 1 → First 10 records
Page 2 → Next 10 records
This improves:
API performance
Response time
User experience
Why Pagination is Important in Web APIs
Let’s understand why pagination is crucial in ASP.NET Core Web API:
1. Improves Performance
Fetching only required records reduces database load and improves speed.
2. Reduces Memory Usage
Large datasets can consume high memory. Pagination keeps responses lightweight.
3. Better User Experience
Users can easily navigate through pages instead of scrolling endlessly.
4. Scalable APIs
Pagination ensures your API works efficiently even when data grows.
Types of Pagination
There are mainly three types of pagination:
1. Offset-Based Pagination
Uses Skip and Take.
Example:
Skip 10 records
Take next 10 records
2. Page Number-Based Pagination
Uses PageNumber and PageSize.
Example:
PageNumber = 2
PageSize = 10
3. Cursor-Based Pagination (Advanced)
Uses a pointer (cursor) instead of page numbers.
Best for large and real-time datasets.
Step-by-Step: Implement Pagination in ASP.NET Core Web API
Let’s implement pagination using a simple example.
Step 1: Create a Model
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
Step 2: Create Pagination Parameters Class
public class PaginationParams
{
public int PageNumber { get; set; } = 1;
public int PageSize { get; set; } = 10;
private const int MaxPageSize = 50;
public void Validate()
{
if (PageNumber <= 0) PageNumber = 1;
if (PageSize <= 0) PageSize = 10;
if (PageSize > MaxPageSize) PageSize = MaxPageSize;
}
}
👉 This ensures:
Default values
Maximum limit to avoid performance issues
Step 3: Modify Repository or Service Layer
public async Task<IEnumerable<Product>> GetProductsAsync(PaginationParams paginationParams)
{
paginationParams.Validate();
return await _context.Products
.Skip((paginationParams.PageNumber - 1) * paginationParams.PageSize)
.Take(paginationParams.PageSize)
.ToListAsync();
}
Join the conversation! Your thoughts help the community grow.