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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With