ASP.NET Web API - Paging and Sorting


Here's an example of an ASP.NET Web API program that implements pagination and sorting and we will check it on testing tool POSTMAN.

Step 1: Create an ASP.NET Web API Project

We use the version of Visual Studio 2019 and .NET Framework 4.7.2 to build the app.

  1. Start Visual Studio and select Create a new project.
  2. In the Create a new project dialog, select ASP.NET Web Application (.NET Framework)-> Next.
  3. In the Configure your new project dialog, enter webapiexample for Project name -> Create.
  4. In the Create a new ASP.NET Web Application dialog, select Web API -> Create

Now build and run the app, you will see the following image shows the application.

ASP.NET web API Paging and Sorting

Step 2: Add one empty ApiController

Add one empty apiController into the app, with the name as PagingController:

  1. Right click Controllers folder -> add -> controller.
  2. In the Add New Scaffolded Item dialog, select Web API in the left pane, and
  3. Web API Controller - Empty -> Add.
  4. In the Add Controller dialog, Change PagingController for controller name > Add.

Step 3: Add code into the controller

We add the following code into the controller.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;

namespace webapiExample.Controllers
{
    public class PagingController : ApiController
    {
        public class Product
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public decimal Price { get; set; }
        }

     private static List _products = new List()
    {
        new Product {Id = 1, Name = "Product 1", Price = 10.99m},
        new Product {Id = 2, Name = "Product 2", Price = 19.99m},
        new Product {Id = 3, Name = "Product 3", Price = 5.99m},
        new Product {Id = 4, Name = "Product 4", Price = 15.99m},
        new Product {Id = 5, Name = "Product 5", Price = 12.99m}
    };

        [System.Web.Http.HttpGet]
        public IHttpActionResult Get(int page = 1, int pageSize = 5, string sortBy = "Id", bool sortAsc = true)
        {
            // Apply sorting
            var sortedProducts = SortProducts(_products.AsQueryable(), sortBy, sortAsc);

            // Calculate total pages
            var totalPages = (int)Math.Ceiling(sortedProducts.Count() / (double)pageSize);

            // Apply pagination
            var products = sortedProducts
                .Skip((page - 1) * pageSize)
                .Take(pageSize)
                .ToList();

            // Create response object
            var response = new
            {
                TotalPages = totalPages,
                PageSize = pageSize,
                CurrentPage = page,
                SortBy = sortBy,
                SortAsc = sortAsc,
                Products = products
            };

            return Ok(response);
        }

        private IQueryable<Product> SortProducts(IQueryable<Product> products, string sortBy, bool sortAsc)
        {
            switch (sortBy)
            {
                case "Id":
                    return sortAsc ? products.OrderBy(p => p.Id) : products.OrderByDescending(p => p.Id);
                case "Name":
                    return sortAsc ? products.OrderBy(p => p.Name) : products.OrderByDescending(p => p.Name);
                case "Price":
                    return sortAsc ? products.OrderBy(p => p.Price) : products.OrderByDescending(p => p.Price);
                default:
                    return products.OrderBy(p => p.Id);
            }
        }
    }
}

Step 4: Once the Postman is successfully installed or added in your browser, Now open the Postman. It will look like the image displayed below.

ASP.NET web API Paging and Sorting

To get the first page of products with a page size of 3, sorted by price in ascending order.

https://localhost:44376/api/Paging?page=1&pageSize=3&sortBy=Price&sortAsc=true

The API endpoint will return a JSON response containing the paginated and sorted products, along with information about the pagination and sorting parameters.

ASP.NET web API Paging and Sorting

To get the second page of products with a page size of 2, sorted by name in descending order:

http://localhost:5000/api/Paging?page=2&pageSize=2&sortBy=Name&sortAsc=false


Next

Top Articles

  1. Why use C#
  2. How to use comment in C#
  3. How to use variables in C#
  4. How to use keywords in C#