public static JsonApiPagination ExtractPagination(this HttpRequestMessage request) { var hasPageNumberParam = false; var hasPageSizeParam = false; var pageNumber = 0; var pageSize = DefaultPageSize; foreach (var kvp in request.GetQueryNameValuePairs()) { if (kvp.Key == PageNumberQueryParam) { hasPageNumberParam = true; if (!int.TryParse(kvp.Value, out pageNumber)) { throw new Exception("Page number must be a positive integer."); } } else if (kvp.Key == PageSizeQueryParam) { hasPageSizeParam = true; if (!int.TryParse(kvp.Value, out pageSize)) { throw new Exception("Page size must be a positive integer."); } } } if (!hasPageNumberParam && !hasPageSizeParam) { return(null); } if ((hasPageNumberParam && !hasPageSizeParam)) { throw new Exception(string.Format("In order for paging to work properly, if either {0} or {1} is set, both must be.", PageNumberQueryParam, PageSizeQueryParam)); } if ((!hasPageNumberParam && hasPageSizeParam)) { throw new Exception(string.Format("In order for paging to work properly, if either {0} or {1} is set, both must be.", PageNumberQueryParam, PageSizeQueryParam)); } if (pageNumber < 0) { throw new Exception("Page number must not be negative."); } if (pageSize <= 0) { throw new Exception("Page size must be greater than or equal to 1."); } JsonApiPagination pagination = new JsonApiPagination(); pagination.PageNumber = pageNumber; pagination.PageSize = pageSize; return(pagination); }
public static IQueryable <T> GeneratePagination <T>(this IQueryable <T> query, JsonApiPagination pagination) { if (pagination != null) { query = query.Skip(pagination.PageNumber * pagination.PageSize).Take(pagination.PageSize); } return(query); }