在ASP.NET Core 2.1 Web API中实现分页 [英] Implement Pagination in ASP.NET Core 2.1 Web API

查看:1192
本文介绍了在ASP.NET Core 2.1 Web API中实现分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我进行了搜索,但并未真正找到有关如何在ASP.NET WebAPI Core 2.1应用程序中实现分页逻辑的文章...

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

我有以下内容

[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;
    }

现在,我希望使用新参数 page pageSize 对我的条目进行分页.说

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

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

我应该通过在其中添加一些http参数来使用GetAll()方法,还是创建一个新方法?在没有pageSize的情况下使用page没有什么意义,我该如何管理?

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?

推荐答案

首先,您可以默认将pageSize值设置为以下值:

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

这篇关于在ASP.NET Core 2.1 Web API中实现分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆