When it comes to pagination of the ASP. NET Web API, consider the following factors:
1, previous page and next page URI
2, Total and total pages
3. Current page and page capacity
What is the return of the data in the server?
We usually write this:
{
Totalcount:10,
Result: [
{id:1, Name: "A"},
{id:2, name: ' B '}
]
}
Above, the paging correlation and entity information are returned to the front end in JSON format. But in this article, try another way: put the paging information in the header and return it to the front end.
Const intMaxPageSize =Ten; [Route ("Api/items", name="Items")] PublicIhttpactionresult Get (intpage =1, ing pageSize =5){ Try { varItems =_repo. GetItem (). Sort (). Where (); if(PageSize >maxpagesize) {PageSize=MaxPageSize; } varTotalCount =items. Count (); varTotalPages = (int) Math.ceiling (Double) totalcount/pageSize); varUrlhelper =NewUrlhelper (Request); varPrevlink = page >1? Urlheloer.link ("Items",New{page= Page-1, PageSize=pageSize, ...}) : ""; varNextLink = Page < totalpages? Urlhelper.link ("Items",New{page= page +1, PageSize=pageSize, ...}) : ""; varPaginationheader =New{currentpage=page, PageSize=pageSize, TotalCount=TotalCount, TotalPages=TotalPages, Previouspagelink=Prevlink, Nextpagelink=NextLink}; //put it in the header.HTTPCONTEXT.CURRENT.RESPONSE.HEADERS.ADD ("x-pagination", Newtonsoft.Json.JsonConvert.SerializeObject (Paginationheader)); varresult =items. Skip (PageSize* (Page-1)) . Take (pageSize). ToList (). Select (e=Itemfactory.createitem (e)); returnOk (Result); } Catch(Exception) {//TODO: Handling Exceptions }}
The client makes the following request:
localhost:4321/api/items?page=2&pagesize=2
There is a X-pagination property 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"
}
Return paging information to the front end in the ASP. NET Web API