Ser*_*rge 6 pagination asp.net-core asp.net-core-webapi asp.net-core-2.1 asp.net-core-webapi-2.1
我进行了搜索,但并未真正找到有关如何在ASP.NET WebAPI Core 2.1应用程序中实现分页逻辑的文章。
我有以下
[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;
}
Run Code Online (Sandbox Code Playgroud)
现在,我希望使用新的参数page和来对条目进行分页pageSize。说
/api/entries?pageSize=3&page=2
Run Code Online (Sandbox Code Playgroud)
我应该GetAll()通过在其中添加一些http参数来使用该方法,还是创建一个新方法?有两种使用没有多大意义page没有pageSize,我该如何管理呢?
Chr*_*att 17
有可以使用的库,例如X.PagedList。坦率地说,分页非常简单明了,因此您可能甚至不需要它。您只需要知道页码,页面大小和结果总数即可。明显的页码来自请求,如果您希望自定义它,则页面大小也可以,或者可以对其进行硬编码。
public ActionResult<List<Entry>> GetAll(int page = 1, int size = 10)
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用Skip和Take获取特定页面的数据:
var query = _context.Entries;
var entries = await query.Skip((page - 1) * size).Take(size).ToListAsync();
var count = await query.CountAsync();
Run Code Online (Sandbox Code Playgroud)
然后,您只需要知道页面的总数即可,可通过以下方式简单地计算:
var totalPages = (int)Math.Ceil(count / (float)size);
Run Code Online (Sandbox Code Playgroud)
由此,您可以计算所需的其他任何内容,即:
var firstPage = 1; // obviously
var lastPage = totalPages;
var prevPage = page > firstPage ? page - 1 : firstPage;
var nextPage = page < lastPage ? page + 1 : lastPage;
Run Code Online (Sandbox Code Playgroud)
首先,您可以将您的pageSize值默认为:
[HttpGet]
public ActionResult<List<Entry>> GetAll(int? page = null, int? pageSize = 10)
{
if (!page.HasValue) {
return _context.Entries.ToList();
}
// do you pagination here
}
Run Code Online (Sandbox Code Playgroud)
但是您也可以查看OData,这似乎是您的情况。它将允许您使用 http 参数查询数据,例如:/api/Entires?$skip=5&$top=5
| 归档时间: |
|
| 查看次数: |
9812 次 |
| 最近记录: |