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. services.AddSingleton<IMovieService, MovieService>();
  11. services.AddMvc();
  12. }
  13. public void Configure(IApplicationBuilder app,IHostingEnvironment env)
  14. {
  15. app.UseDeveloperExceptionPage();
  16. app.UseMvcWithDefaultRoute();
  17. }

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.

Source Code

GitHub