Usage:
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net.Http; using System.Web.Http; using System.Web.Http.OData.Query; namespace WebApiTest.Controllers { public class ValuesController : ApiController { private const int PAGESIZE = 25; // GET api/values [ActionName("Default")] public PageOfResultsGet(ODataQueryOptions queryOptions) { var data = new Poco[] { new Poco() { id = 1, name = "one", type = "a" }, new Poco() { id = 2, name = "two", type = "b" }, new Poco() { id = 3, name = "three", type = "c" }, new Poco() { id = 4, name = "four", type = "d" }, new Poco() { id = 5, name = "five", type = "e" }, new Poco() { id = 6, name = "six", type = "f" }, new Poco() { id = 7, name = "seven", type = "g" }, new Poco() { id = 8, name = "eight", type = "h" }, new Poco() { id = 9, name = "nine", type = "i" } }; var t = new ODataValidationSettings() { MaxTop = PAGESIZE }; queryOptions.Validate(t); var s = new ODataQuerySettings() { PageSize = PAGESIZE }; IEnumerable results = (IEnumerable )queryOptions.ApplyTo(data.AsQueryable(), s); int skip = queryOptions.Skip == null ? 0 : queryOptions.Skip.Value; int take = queryOptions.Top == null ? PAGESIZE : queryOptions.Top.Value; long count = Request.GetInlineCount() ?? 0; PageOfResults page = new PageOfResults (results, skip, take, count); return page; } } }
Class:
using System; using System.Collections.Generic; using System.Linq; using System.Xml.Serialization; namespace WebApiTest { [Serializable] [XmlRoot("Page")] public class PageOfResults<T> { public PageOfResults() { } private readonly IEnumerable<T> _results; private long _skip; private long _take; private long _total; public PageOfResults(IEnumerable<T> items, int skip, int take, long total) { _results = items;//.ToList(); _skip = skip; _take = take; _total = total; } [XmlAttribute("skip")] public long Skip { get { return _skip; } set { } } [XmlAttribute("top")] public long Top { get { return _take; } set { } } [XmlAttribute("total")] public long Total { get { return _total; } set { } } [XmlArray("Results")] public List<T> Items { get { return _results.ToList(); } } } }