ASP.NET Web API中把分页信息放Header中返回给前端

时间:2022-06-20 03:14:31

谈到ASP.NET Web API的分页,考虑的因素包括:

1、上一页和下一页的uri
2、总数和总页数
3、当前页和页容量

接着是服务端的数据以怎样的形式返回?

我们通常这样写:

{
    totalCount:10,
    result: [
        {id:1, name:"a"},
        {id:2, name:"b"}
    ]
}

以上,把分页相关和实体信息以json格式返回给前端。但在本篇,尝试另外一种方式:把分页信息放在Header中返回给前端。

const int maxPageSize = ;

[Route("api/items", Name="items")]
public IHttpActionResult Get(int page = , ing pageSize = )
{
try
{
var items = _repo.GetItem()
.sort()
.Where(); if(pageSize > maxPageSize)
{
pageSize = maxPageSize;
} var totalCount = items.Count();
var totalPages = (int)Math.Ceiling((double)totalCount/pageSize); var urlHelper = new UrlHelper(Request);
var prevLink = page > ? UrlHeloer.Link("items", new {
page = page -,
pageSize = pageSize,
...
}) : ""; var nextLink = page < totalPages? urlHelper.Link("items", new {
page = page + ,
pageSize = pageSize,
...
}) : ""; var paginationHeader = new
{
currentPage = page,
pageSize = pageSize,
totalCount = totalCount,
totalPages = totalPages,
previousPageLink = prevLink,
nextPageLink = nextLink
}; //放到Header中
HttpContext.Current.Response.Headers.Add("X-Pagination", Newtonsoft.Json.JsonConvert.SerializeObject(paginationHeader)); var result = items
.Skip(pageSize * (page - ))
.Take(pageSize)
.ToList()
.Select(e => ItemFactory.CreateItem(e)); return Ok(result); }
catch(Exception)
{
//TODO:处理异常
}
}

客户端发出如下请求:

localhost:4321/api/items?page=2&pagesize=2

在响应中有一个X-Pagination属性:

X-Pagination:{
    "currentPage":2,
    "pageSize":2,
    "totalPages":4,
    "previousPageLink": "http://localhost:4321/api/items?page=1&pageSize=2"
    "nextPageLink":"http://localhost:4321/api/items?page=3&pageSize=2"
}