WebApi.Pagination allows you to easily add Range Header-based pagination to existing WebAPI endpoints that operate on IQueryable
data sources.
NuGet package:
Simply add the [Pagination]
attribute to a controller method with an IQueryable<T>
return type.
Sample:
[Pagination]
public IQueryable<Person> Get()
{
return Database.Persons.OrderBy(x => x.Name);
}
If you add any other filter attributes to your methods make sure the [Pagination]
attribute is listed last. Otherwise modifications to the response made by other filters will be lost.
Use [Pagination(LongPolling = true)]
to enable long polling.
If your controller method returns an HttpResponseMessage
rather than a message content, you can use the .CreateResponsePagination()
extension method for HttpRequestMessage
to build a paginated response.
Sample:
[Pagination]
public HttpResponseMessage Get(HttpRequestMessage request)
{
return request.CreateResponsePagination(
Database.Persons.OrderBy(x => x.Name));
}
Use .CreateResponsePaginationAsync(..., longPolling: true)
to enable long polling.
The source code includes a sample project that uses demonstrates the usage of WebApi.Pagination. You can build and run it using Visual Studio 2015. By default the instance will be hosted by IIS Express at http://localhost:2085/attributes/
and http://localhost:2085/extension-methods/
.
Request:
GET /resource
Range: elements=2-5
Response:
206 Partial Content
Content-Range: elements 2-3/5
[ 2, 3 ]
Request:
GET /resource
Range: elements=-2
Response:
206 Partial Content
Content-Range: elements 4-5/5
[ 4, 5 ]
Request:
GET /resource
Range: elements=2-
Response:
206 Partial Content
Content-Range: elements 2-5/5
[ 2, 3, 4, 5 ]
Initial request:
GET /resource
Range: elements=0-
Response after timeout with no new content:
416 Requested Range not satisfiable
Client keeps polling automatically. Request:
GET /resource
Range: elements=0-
Response after delay until new content became available:
206 Partial Content
Content-Range: elements 0-1/*
[ 0, 1 ]
Client keeps polling automatically. Request:
GET /resource
Range: elements=2-
Response after delay until new content became available:
206 Partial Content
Content-Range: elements 2-3/4
[ 2, 3 ]
Client stops polling because content range with specified length (4
instead of *
) indicates the end has been reached.