Ads

Web API 11 : Pagination in ASP.NET Core Web API

Hello All,

Welcome back!

In this article, we are going to look at how we can implement the simple pagination.

What is Pagination?

Let say we have an endpoint in our API which return millions of records with a single request, there are 100s of users that are going to use this endpoint by requesting all the data in a single go at the same time. This would nearly kill our server and lead to several issues including security.

Pagination is logic where we get partial results from an API.

Ok, Lets Implement the pagination

Implementation:

1. Open Visual Studio


2. Create a New Project


3. Choose project "ASP.NET Core Web API"


4. Enter Project Name, Select Location and Clock Next


5. Select Framework .NET Core 6.0 and Click Create


6. Delete the un-used classes and objects(deleted the highlighted class files)


7. Cool, we have done, Its time to create the Entity Class before that we will create the folder called Model and all the entity will be added in  that.




Inside Models folder, Lets create class file called Learning.cs and the fields

namespace My.Simple.Web.API.Models
{
    public class Learning
    {
        public int LearningId { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public DateTime DateStarted { get; set; }
        public DateTime DateCompleted { get; set; }
    }
}

Create one more class file called ServiceParameter.cs, which is required for Pagination

namespace My.Simple.Web.API.Models
{
    public class ServiceParameter
    {
        const int maxPageSize = 50;
        public int PageNumber { get; set; } = 1;
        private int _pageSize = 10;
        public int PageSize
        {
            get
            {
                return _pageSize;
            }
            set
            {
                _pageSize = (value > maxPageSize) ? maxPageSize : value;
            }
        }
    }
}

8. Right Click on Controller folder and Add Controller

Add ==> Controller ==> Empty API Controller and name it to LearningController.cs

First add the sample static data

List<Learning> learningList = new List<Learning>()
        {
            new Learning
            {
                Title="Course1",
                Description="Course1 Description",
                LearningId=1,
                DateStarted=DateTime.Now,
                DateCompleted=DateTime.Now
            },
           new Learning
            {
                Title="Course2",
                Description="Course2 Description",
                LearningId=2,
                DateStarted=DateTime.Now,
                DateCompleted=DateTime.Now
            },new Learning
            {
                Title="Course3",
                Description="Course3 Description",
                LearningId=3,
                DateStarted=DateTime.Now,
                DateCompleted=DateTime.Now
            },new Learning
            {
                Title="Course4",
                Description="Course4 Description",
                LearningId=4,
                DateStarted=DateTime.Now,
                DateCompleted=DateTime.Now
            },new Learning
            {
                Title="Course5",
                Description="Course5 Description",
                LearningId=5,
                DateStarted=DateTime.Now,
                DateCompleted=DateTime.Now
            },new Learning
            {
                Title="Course6",
                Description="Course6 Description",
                LearningId=6,
                DateStarted=DateTime.Now,
                DateCompleted=DateTime.Now
            },new Learning
            {
                Title="Course7",
                Description="Course7 Description",
                LearningId=7,
                DateStarted=DateTime.Now,
                DateCompleted=DateTime.Now
            },new Learning
            {
                Title="Course8",
                Description="Course8 Description",
                LearningId=8,
                DateStarted=DateTime.Now,
                DateCompleted=DateTime.Now
            },new Learning
            {
                Title="Course9",
                Description="Course9 Description",
                LearningId=9,
                DateStarted=DateTime.Now,
                DateCompleted=DateTime.Now
            },new Learning
            {
                Title="Course10",
                Description="Course10 Description",
                LearningId=10,
                DateStarted=DateTime.Now,
                DateCompleted=DateTime.Now
            },
        };

Add HttpGet method called Get and Provide the Route learning-list

        [HttpGet("learning-list")]
        public IActionResult Get([FromQuery]ServiceParameter serviceParameter)
        {
            var response =
            learningList.OrderBy(on => on.Title)
            .Skip((serviceParameter.PageNumber - 1) * serviceParameter.PageSize)
            .Take(serviceParameter.PageSize)
            .ToList();
            return Ok(response);
        }

In above code we are passing ServiceParameter as an argument

Here We are using constant maxPageSize to restrict our API to a maximum of 50 records and also We have public properties – called PageNumber and PageSize. 

Default PageNumber will be set to 1, and PageSize to 10 when user will not set any value

How It Works?

Here is the simple demonstration.

Consider that we need to get the results for the fourth page of our website, counting 10 as the number of records we want. 
That would mean we want to skip the first ((4 – 1) * 10) = 30 results, and then take the next 10 and return them to the service consumer/client.

Testing the Solution:

We have 10 static records.

Lets run the service and get the 5 records for page number 1

https://localhost:7289/api/Learning/learning-list?PageNumber=1&PageSize=5

Response will be

[
  {
    "learningId": 1,
    "title": "Course1",
    "description": "Course1 Description",
    "dateStarted": "2022-05-14T15:56:22.3544592+05:30",
    "dateCompleted": "2022-05-14T15:56:22.3544618+05:30"
  },
  {
    "learningId": 10,
    "title": "Course10",
    "description": "Course10 Description",
    "dateStarted": "2022-05-14T15:56:22.3544649+05:30",
    "dateCompleted": "2022-05-14T15:56:22.3544649+05:30"
  },
  {
    "learningId": 2,
    "title": "Course2",
    "description": "Course2 Description",
    "dateStarted": "2022-05-14T15:56:22.3544626+05:30",
    "dateCompleted": "2022-05-14T15:56:22.3544627+05:30"
  },
  {
    "learningId": 3,
    "title": "Course3",
    "description": "Course3 Description",
    "dateStarted": "2022-05-14T15:56:22.3544628+05:30",
    "dateCompleted": "2022-05-14T15:56:22.3544629+05:30"
  },
  {
    "learningId": 4,
    "title": "Course4",
    "description": "Course4 Description",
    "dateStarted": "2022-05-14T15:56:22.3544631+05:30",
    "dateCompleted": "2022-05-14T15:56:22.3544632+05:30"
  }
]

Cool! We now have a pagination in place.

Thats it for this article. You can down complete source code here Source Code

See you in next article take care bye.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !