谈到ASP.NET Web API的分页,考虑的因素包括:
1、上一页和下一页的uri2、总数和总页数3、当前页和页容量接着是服务端的数据以怎样的形式返回?我们通常这样写:{ totalCount:10, result: [ {id:1, name:"a"}, {id:2, name:"b"} ]}以上,把分页相关和实体信息以json格式返回给前端。但在本篇,尝试另外一种方式:把分页信息放在Header中返回给前端。const int maxPageSize = 10;[Route("api/items", Name="items")]public IHttpActionResult Get(int page = 1, ing pageSize = 5){ 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 > 1 ? UrlHeloer.Link("items", new { page = page -1, pageSize = pageSize, ... }) : ""; var nextLink = page < totalPages? urlHelper.Link("items", new { page = page + 1, 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 - 1)) .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"}