WebAPI Pagination

Paginate a ASP.NET Core API

In this post, I will show you how to implement pagination on an ASP.NET Core API (.NET 5) with other features like searching text and sorting.

To make this tutorial simple and short, I will use the base repo of the last tutorial. You can find it here. I just renamed it "Pagination".

For this tutorial, you'll need to install the package "System.Linq.Dynamic.Core".

First, we need to create a class "PaginationFilter" like the following:

PaginationFilter class

Now, create the missing enum "OrderBy":

The next step is to create an extension for queries, to order the results by a specif property, search text and paginate them.
Create a static class and a static method "Paginate" like this:

Pagination extension

Now create the helper methods in the same file:

Helper methods

The first method, is going to return the sort query like ".OrderBy(x => x.name_of_the_property)".
The second method returns the Where query with the provided searchText property.

Create a new class for the response containing the data, total pages, and total records.

PagedResponse class

Now, it's time to use the pagination extension. On the controllers, for example, the ProductsController we only have to update it like this:

Controller with pagination

Run it, and you can test it on swagger! Insert some records before. Swagger

You can find the repo on my GitHub

Hope you enjoyed it and learned something new!

Header image from unsplash

Do you have any doubt, or did you detect an error? Contact me!