Skip to main content

How to define a REST service with pagination support - Part 2

Part 1:
Part 2:
In this post we will see how we can implement using ApiController, a REST service that expose a list of items using pagination.
In the previous post related to this subject we define the REST API for pagination. We saw how important is for clients to has all the information directly in the message itself. For example the next page URL should be send by the service, not constructs by the clients.
The below example contains the request and response of our REST service.
GET /api/cars?pageNumber=3&pageSize=20

Get items from database
Let’s assume that we are using Entity Framework to fetch data from database. To be able to get only the items that we need for the requested page we will need to use a LINQ expression that contains

  • Skip – to get only the items starting from a specific location
  • Take – take only the items that are needed for the current page

Unfortunately, Skip and Take commands can be used only in combination with OrderBy. Because of this we will need to call and apply an order by before each query. This is needed because this is the only way how EF can guarantee that the items that are returned are the expected one (items from database are not orders).
List<Car> entities = carSet
                                        .OrderBy(x => x.Id)
                                        .Skip((pageNumber - 1) * pageSize)
On top of this we will need to get the total number of items. For this we will to make another query that retrieves the total available items.
int totalItems = carSet.Count();
Generate response
The response from the repository can we wrapped  in a class that extends List<T> and has a property with all the information related to pagination (page number, size, items count).
public class Page<TItem> : List<TItem>
    public Page()

    public Page(IEnumerable<TItem> collection, Paging paging)
        : base(collection)
        Paging = paging;

    public Paging Paging { get; set; }
Class that contains all the information related to pagination:
public class Paging
    public int PageNumber { get; set; }

    public int PageSize { get; set; }

    public int TotalPages { get; set; }

    public int TotalItemsCount { get; set; }

    public bool HasNext
            return TotalPages > PageNumber;

    public bool HasPrev
            return PageNumber > 1 && PageNumber <= TotalPages;
Next we will need to use a dynamic object to generate the response message that contains all the necessary information.
public class PaginationUtility
    private const string PageNumberQueryName = "page";
    private const string PageSizeQueryName = "pageSize";
    private const string ErrorMessageForInvalidPage = "This page don't exist.";

    public HttpResponseMessage CreateResponseMessageForPaginaionRequests<TEntity>(Page<TEntity> requestedPage,
        HttpRequestMessage request)
        dynamic bodyMessage = CreateResponseBody(requestedPage, request);

        HttpResponseMessage responseMessage = requestedPage.Count == 0 ||
                                                requestedPage.Paging.PageNumber > requestedPage.Paging.TotalPages
            ? CreateResponseMessageForInvalidPagingRequest(request)
            : CreateResponseMessageForPagingRequest(request);

        responseMessage.Content = new StringContent(JsonConvert.SerializeObject(bodyMessage));

        return responseMessage;

    private static dynamic CreateResponseBody<TEntity>(Page<TEntity> requestedPage, HttpRequestMessage requestMessage)
        Paging currentPage = requestedPage.Paging;
        string uriPath = requestMessage.RequestUri.GetLeftPart(UriPartial.Path);

        string prevPageLink = currentPage.HasPrev
            ? GeneratePaginationNavigationUri(currentPage.PageNumber - 1, currentPage.PageSize, uriPath)
            : string.Empty;

        string nextPageLink = currentPage.HasNext
            ? GeneratePaginationNavigationUri(currentPage.PageNumber + 1, currentPage.PageSize, uriPath)
            : string.Empty;

        string firstPageLink = currentPage.TotalPages == 0
            ? string.Empty
            : GeneratePaginationNavigationUri(1, currentPage.PageSize, uriPath);
        string lastPageLink = currentPage.TotalPages == 0
            ? string.Empty
            : GeneratePaginationNavigationUri(requestedPage.Paging.TotalPages, currentPage.PageSize, uriPath);

        dynamic pagInformation = new
            pageNumber = currentPage.PageNumber,
            pageSize = currentPage.PageSize,
            totalPages = currentPage.TotalPages,
            totalItemsCount = currentPage.TotalItemsCount,
            items = requestedPage.ToList()

        return pagInformation;

    private static HttpResponseMessage CreateResponseMessageForInvalidPagingRequest(HttpRequestMessage request)
        HttpResponseMessage errorResponse = request.CreateErrorResponse(
        return errorResponse;

    private static HttpResponseMessage CreateResponseMessageForPagingRequest(HttpRequestMessage request)
        HttpResponseMessage response = request.CreateResponse(HttpStatusCode.OK);
        return response;

    private static string GeneratePaginationNavigationUri(int page, int pageSize, string uriPath)
        UriBuilder prevUriBuilder = new UriBuilder(uriPath);
        NameValueCollection prevQuery = HttpUtility.ParseQueryString(prevUriBuilder.Query);
        prevQuery.Add(PageNumberQueryName, page.ToString(CultureInfo.InvariantCulture));
        prevQuery.Add(PageSizeQueryName, pageSize.ToString(CultureInfo.InvariantCulture));
        prevUriBuilder.Query = prevQuery.ToString();
        return prevUriBuilder.ToString();
Our controller is very simple, it only has to call the repository method that gets the items and format the response using the above code.
 public HttpResponseMessage Get(int page, int pageSize)

We are done. In this post we saw how easy we can expose a REST API with pagination support using EF and ApiController.


Popular posts from this blog

ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded

Today blog post will be started with the following error when running DB tests on the CI machine:
threw exception: System.InvalidOperationException: The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer' registered in the application config file for the ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded. Make sure that the assembly-qualified name is used and that the assembly is available to the running application. See for more information. at System.Data.Entity.Infrastructure.DependencyResolution.ProviderServicesFactory.GetInstance(String providerTypeName, String providerInvariantName) This error happened only on the Continuous Integration machine. On the devs machines, everything has fine. The classic problem – on my machine it’s working. The CI has the following configuration:

TeamCity.NET 4.51EF 6.0.2VS2013
It seems that there …

How to check in AngularJS if a service was register or not

There are cases when you need to check in a service or a controller was register in AngularJS.
For example a valid use case is when you have the same implementation running on multiple application. In this case, you may want to intercept the HTTP provider and add a custom step there. This step don’t needs to run on all the application, only in the one where the service exist and register.
A solution for this case would be to have a flag in the configuration that specify this. In the core you would have an IF that would check the value of this flag.
Another solution is to check if a specific service was register in AngularJS or not. If the service was register that you would execute your own logic.
To check if a service was register or not in AngularJS container you need to call the ‘has’ method of ‘inhector’. It will return TRUE if the service was register.
if ($injector.has('httpInterceptorService')) { $httpProvider.interceptors.push('httpInterceptorService&#…

Fundamental Books of a Software Engineer (version 2018)

More then six years ago I wrote a blog post about fundamental books that any software engineer (developer) should read. Now it is an excellent time to update this list with new entries.

There are 5 different categories of books, that represent the recommended path. For example, you start with Coding books, after that, you read books about Programming, Design and so on.
There are some books about C++ that I recommend not because you shall know C++, only because the concepts that you can learn from it.


Writing solid codeCode completeProgramming Pearls, more programming pearls(recommended)[NEW] Introduction to Algorithms


Refactoring (M. Fowler)Pragmatic ProgrammerClean code[NEW] Software Engineering: A Practitioner's Approach[NEW] The Mythical Man-Month[NEW] The Art of Computer Programming


Applying UML and Patterns (GRASP patterns)C++ coding standards (Sutter, Alexandrescu)The C++ programming language (Stroustrup, Part IV)Object-oriented programming (Peter Coad)P…