Paging In ASP.NET Core 2.0 Web API

Problem

How to implement paging in ASP.NET Core Web API.

Solution

In an empty project, update the Startup class to add services and middleware for MVC.

Add models to hold link and paging data.

Create a type to hold the paged list.

Add a service and domain model.

Add output models (to send data via API).

Add a controller for the API with service injected via constructor.

Output

Discussion

Let’s walk through the sample code step-by-step.

  • Paging information, i.e., page number and page size, is usually received via query parameters. The POCO PagingParams simply holds this information and passes it to service (or repository).

  • Service will then wrap the results (a list) in another custom type PagedList so that it can hold the paging metadata along with the original list. GetHeader() method on PagedList returns a POCO PagingHeader which is used later to populate X-Pagination

  • Back in the controller, we add the pagination header to HTTP response. This header can be read by the client and looks like.

  • We build our output model MovieOutputModel and return status code 200 (OK). The output model contains,

    • Paging information that is essentially the PagingHeader POCO and contains properties like TotalItems, PageNumber, PageSize, and TotalPages.

    • Links to the current, next and previous pages. These are created with the help of framework provided IUrlHelper interface which was registered in the service container in Startup.

    • List of movies. As discussed in the previous post (CRUD), we mapped the domain model to an output model (MovieInfo in this case).
Source Code

GitHub

Up Next
    Ebook Download
    View all
    Learn
    View all