ASP.NET Web API中把分頁資訊放Header中返回給前端

Darren Ji發表於2016-01-21

 

談到ASP.NET Web API的分頁,考慮的因素包括:

1、上一頁和下一頁的uri
2、總數和總頁數
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"
}

 

相關文章