Implement Pagination in ASP.NET Core 2.1 Web API

佐手、 提交于 2020-02-02 02:48:09

问题


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?


回答1:


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




回答2:


There are libraries, such as X.PagedList you can use. Frankly, pagination is pretty straight-forward, so you may not even need that. All you need to know is the page number, page size, and total number of results. The page number obvious comes from the request, and the page size can as well, if you want it customizable, or you can hard-code it.

public ActionResult<List<Entry>> GetAll(int page = 1, int size = 10)

Then, you can use Skip and Take to get the data for a particular page:

var query = _context.Entries;
var entries = await query.Skip((page - 1) * size).Take(size).ToListAsync();
var count = await query.CountAsync();

Then, all you need to know is the total number of pages, which can be calculated simply via:

var totalPages = (int)Math.Ceil(count / (float)size);

From that, you can calculate anything else you need, i.e.:

var firstPage = 1; // obviously
var lastPage = totalPages;
var prevPage = page > firstPage ? page - 1 : firstPage;
var nextPage = page < lastPage ? page + 1 : lastPage;



回答3:


I've just created a PagingTagHelper for ASP.NET Core Razor pages to render paging control easily with just the basic parameters, the simplest setup looks like below:

<paging total-records="Model.TotalRecords" page-no="Model.PageNo">
</paging>

all you need is to provide total records and page number for it to run. The default query string parameters are "p" for page number and "s" for page size, however, it is customizable/localizable, you can change all the settings according to your own requirements.

you can install it from nuget:

Install-Package LazZiya.TagHelpers -Version 1.0.2

then you need to add the tag helper to the _ViewImports.cshtml file:

@addTagHelper *, LazZiya.TagHelpers

http://ziyad.info/en/articles/21-Paging_TagHelper_for_ASP_NET_Core

more documentations and live demo will be available soon.



来源:https://stackoverflow.com/questions/52331318/implement-pagination-in-asp-net-core-2-1-web-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!