Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implement Pagination in ASP.NET Core 2.1 Web API

I searched, but did't really found articles on how to implement pagination logic in an ASP.NET WebAPI Core 2.1 application...

I have the following

[Route("api/[controller]")]
[ApiController]
[EnableCors("AllowMyOrigin")]
public class EntriesController : ControllerBase
{
    private readonly EntriesContext _context;

    public EntriesController(EntriesContext context) {
        _context = context;

        if (_context.Entries.Count() == 0) {
            _context.Entries.Add(new Entry { From = "default", To = "default" });
            _context.SaveChanges();
        }
    }

    [HttpGet]
    public ActionResult<List<Entry>> GetAll() {
        return _context.Entries.ToList();
    }

    [HttpGet("{id}", Name = "GetEntry")]
    public ActionResult<Entry> GetById(long id) {
        var item = _context.Entries.Find(id);
        if (item == null) { return NotFound(); }
        return item;
    }

Now, I want my entries to be paginated using new params page and pageSize. Say

/api/entries?pageSize=3&page=2 

Should I use the GetAll() method by adding some http params to it, or rather create a new method? There are no much sense to use page without pageSize, how do I manage this?

like image 709
serge Avatar asked Sep 14 '18 11:09

serge


People also ask

How can we implement pagination in asp net core?

How to implement paging in ASP.NET Core Web API. In an empty project, update the Startup class to add services and middleware for MVC. Add models to hold link and paging data. Create a type to hold the paged list.

What is pagination in Web API?

Pagination is the process of splitting data into discrete pages, and you should implement it when you are building RESTful Web APIs that potentially serve huge amount of data. Imagine you have thousands or maybe millions of records in your database and your API endpoint try to return all of them at once.

How pagination is implemented?

For example, you can implement pagination using links to new pages on your ecommerce site, or using JavaScript to update the current page. Load more and infinite scroll are generally implemented using JavaScript.


1 Answers

First of all, you can default you pageSize value to something:

[HttpGet]
public ActionResult<List<Entry>> GetAll(int? page = null, int? pageSize = 10) 
{
    if (!page.HasValue) {
        return _context.Entries.ToList();
    }

    // do you pagination here
}

But you also may look at OData, it seems to be your case. It will allow you to query your data using http params, e.g.: /api/Entires?$skip=5&$top=5

like image 119
Alex Riabov Avatar answered Oct 21 '22 15:10

Alex Riabov