在ASP.NET Core 2.1 Web API中实现分页

编程入门 行业动态 更新时间:2024-10-19 01:27:35
本文介绍了在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 }

但是您也可以查看 OData ,这似乎是您的情况.它将允许您使用http参数查询数据,例如:/api/Entires?$skip=5&$top=5

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中实现分页

本文发布于:2023-11-13 15:11:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1584672.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:分页   Core   NET   ASP   API

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!