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.

  1. public void ConfigureServices(IServiceCollection services)  
  2. {    
  3.       services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();    
  4.       services.AddScoped<IUrlHelper>(factory =>    
  5.       {    
  6.           var actionContext = factory.GetService<IActionContextAccessor>()    
  7.                                      .ActionContext;    
  8.           return new UrlHelper(actionContext);    
  9.       });    
  10.     
  11.       services.AddSingleton<IMovieService, MovieService>();    
  12.     
  13.       services.AddMvc();    
  14. }    
  15.     
  16. public void Configure(IApplicationBuilder app,IHostingEnvironment env)    
  17. {    
  18.       app.UseDeveloperExceptionPage();    
  19.       app.UseMvcWithDefaultRoute();    
  20. }   

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