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

來源:互聯網
上載者:User

標籤:

 

談到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"
}

 

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.