Adding pagination for link headers in Web Api 2

Currently, in my "Rest" service, I am returning paged data using the following model.

public class PagedResults<T> { public List<LinkModel> Links { get; set; } public int TotalCount { get; set; } public double TotalPages { get; set; } public List<T> Results { get; set; } } 

This works well, but I came across the following post.

http://www.vinaysahni.com/best-practices-for-a-pragmatic-restful-api#pagination

My curiosity has been reached; he mentions using HTTP headers to return links and pagination information. Although the message mentions RFC 5988, I could not disclose what this really means? Was it actually adopted as some kind of standard?

Question in ASP.Net Web API 2, is there any support for adding pagination information in the link header? I used intellisense to view the headers of the HTTP responses, and I did not find any links or something like that.

I found this post, but it actually does not answer my question about facilitating this in Web API 2.

Associate headers with link elements for RESTful JSON

+5
source share
2 answers

You can check mine here , which shows how to add pagination as a β€œcustom” (X-Pagination) header, below is an example of code that might help:

  public IEnumerable<StudentBaseModel> Get(int page = 0, int pageSize = 10) { IQueryable<Student> query; query = TheRepository.GetAllStudentsWithEnrollments().OrderBy(c => c.LastName); var totalCount = query.Count(); var totalPages = (int)Math.Ceiling((double)totalCount / pageSize); var urlHelper = new UrlHelper(Request); var prevLink = page > 0 ? urlHelper.Link("Students", new { page = page - 1, pageSize = pageSize }) : ""; var nextLink = page < totalPages - 1 ? urlHelper.Link("Students", new { page = page + 1, pageSize = pageSize }) : ""; var paginationHeader = new { TotalCount = totalCount, TotalPages = totalPages, PrevPageLink = prevLink, NextPageLink = nextLink }; System.Web.HttpContext.Current.Response.Headers.Add("X-Pagination", Newtonsoft.Json.JsonConvert.SerializeObject(paginationHeader)); var results = query .Skip(pageSize * page) .Take(pageSize) .ToList() .Select(s => TheModelFactory.CreateSummary(s)); return results; } 
+12
source

In .Net MVC, adding link headers is trivial. According to the IETF, they are separated by a comma, therefore:

 HttpContext.Response.Headers.Add("Link", string.Join(",", pagedResult.Links)); 

Note: pagedResult is in an instance of your PagedResult<T> class.

This can be used in conjunction with the Taiseer X-Pagination above.

0
source

Source: https://habr.com/ru/post/1203547/


All Articles