ASP. NET Web API puts paging information in the Header and returns it to the front-end. apiheader
When talking about pagination of ASP. NET Web APIs, the following factors are taken into account:
1. uri of the previous and next pages
2. Total and total pages
3. Current page and page capacity
What is the form of data returned by the server?
We usually write as follows:
{
TotalCount: 10,
Result :[
{Id: 1, name: ""},
{Id: 2, name: "B "}
]
}
Above, the page-related and entity information is returned to the front-end in json format. However, in this article, try another method: Put the paging information in the Header and return it to the front-end.
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 }; // put HttpContext in the Header. 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: Exception Handling }}
The client sends the following request:
Localhost: 4321/api/items? Page = 2 & pagesize = 2
There is an X-Pagination attribute in the response:
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"
}