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:
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
Now create the helper methods in the same file:
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.
Now, it's time to use the pagination extension. On the controllers, for example, the ProductsController we only have to update it like this:
Run it, and you can test it on swagger! Insert some records before.
You can find the repo on my GitHub
Hope you enjoyed it and learned something new!
Header image from unsplash