Paging is a useful concept in any API. Here’s an example of one that I use pretty frequently when making APIs in ASP.NET Web API.
You can download an example project (complete with unit tests!) here.
The steps we’re going to take to complete this task are as follows:
- Setup our paging model
- Define our entity and API models
- Create our easy-to-use paging method that will magically turn an
IQueryable
into a paged set of data
This example in particular requires AutoMapper, which will allow us to easily map our entities to our returned API models. I also use Entity Framework to store and retrieve data, though that is not the focus of this particular project. For the record – you should ALWAYS use API models (or DTOs, if you prefer) to do work through controllers. Tarsier Joudeh, a Microsoft MVP for ASP.NET, calls it the “model factory pattern” and that’s how I typically refer to it. That, or just API models. (Another way to think of API models: they hold the same purpose as a view model, but they’re not called that cause there’s no views.) It’s a little bit more code up front, but will keep your code clean and enforce separation of concerns in the long run. This has several advantages:
- Lets you control what data is returned to the client
- Helps avoid binding to undocumented properties on
PUT
s/POST
s, which can be a pretty big security concern
- Maintains a separation of concerns (This object returns data to the client, this object is a database entity, etc.)
1. Create and Define a Paging Model
public class PagedResults<T>
{
public int PageNumber { get; set; }
public int PageSize { get; set; }
public int TotalNumberOfPages { get; set; }
public int TotalNumberOfRecords { get; set; }
public string NextPageUrl { get; set; }
public IEnumerable<T> Results { get; set; }
}
We have our PageNumber
and PageSize
, which should match exactly what you requested (if you requested page 1 and page size 10, you should have a PageNumber
of 1
and a PageSize
of 10
. These fields are included in the event you don’t want to require a page number or page size in your paged API.)
You have some Results
, which represents the actual objects being returned.
There is a TotalNumberOfRecords
and TotalNumberOfPages
, which returns totals for the returned objects. If there are 100 total records and you’re requesting 15 records per page, you should expect that TotalNumberOfPages
will return 7 pages.
Finally, one of the most useful properties in this model is NextPageUrl
. NextPageUrl
makes it very easy to get the next page in the set by providing the URL to that next resource for you.
2. Define your Entities and Your API Models (You Do Use Separate Models for Returning Data, Right?)
public class Employee
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string SocialSecurityNumber { get; set; } public ICollection<Todo> TodoList { get; set; } = new List<Todo>();
}
public class EmployeeModel
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public ICollection<TodoModel> TodoList { get; set; }
}
public class Todo
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public Employee Employee { get; set; }
}
public class TodoModel
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
public class EntityContext : DbContext
{
public virtual DbSet<Employee> Employees { get; set; }
public virtual DbSet<Todo> Todos { get; set; }
}
Note that in this example we are using Entity Framework for data storage.
3. Map Them Together Using AutoMapper
AutoMapper allows us to easily create the EmployeeModel
from the Employee
without writing and maintaining factory methods. All properties with the same name from Employee
will be set on EmployeeModel
. A lot of awesomeness in one little library.
Mapper.CreateMap<Employee, EmployeeModel>();
Mapper.CreateMap<Todo, TodoModel>();
4. Create the Paged Set of Data
I like to use the following CreatePagedResults
method below on my controller base class – it does all of the heavy lifting for you.
public class EmployeesController : BaseController
{
public EntityContext EntityContext { get; }
protected EmployeesController(EntityContext context)
{
EntityContext = context;
}
public async Task<IHttpActionResult> Get(int? page = null,
int pageSize = 10, string orderBy = nameof(Employee.Id), bool ascending = true)
{
if (page == null)
return Ok(await EntityContext.Employees.ToListAsync());
var employees = await CreatePagedResults<Employee, EmployeeModel>
(EntityContext.Employees, page.Value, pageSize, orderBy, ascending);
return Ok(employees);
}
protected async Task<PagedResults<TReturn>> CreatePagedResults<T, TReturn>(
IQueryable<T> queryable,
int page,
int pageSize,
string orderBy,
bool ascending)
{
var skipAmount = pageSize * (page - 1);
var projection = queryable
.OrderByPropertyOrField(orderBy, ascending)
.Skip(skipAmount)
.Take(pageSize).ProjectTo<TReturn>();
var totalNumberOfRecords = await queryable.CountAsync();
var results = await projection.ToListAsync();
var mod = totalNumberOfRecords % pageSize;
var totalPageCount = (totalNumberOfRecords / pageSize) + (mod == 0 ? 0 : 1);
var nextPageUrl =
page == totalPageCount
? null
: Url?.Link("DefaultApi", new {
page = page + 1,
pageSize,
orderBy,
ascending
});
return new PagedResults<TReturn>
{
Results = results,
PageNumber = page,
PageSize = results.Count,
TotalNumberOfPages = totalPageCount,
TotalNumberOfRecords = totalNumberOfRecords,
NextPageUrl = nextPageUrl
};
}
}
A couple of important things to note:
- The
Url.Link
method assumes that you have the default Web API route called DefaultApi
setup in your RouteConfig
. If you don’t, you might have to tweak this example to work for you.
- This example uses an extension method called
OrderByPropertyOrField
which (if you haven’t guessed) orders the IQueryable
by the specified property, with a boolean to determine whether or not the order by should be ascending or descending. This string
points to a property or field name of the entity type represented by IQueryable
. The extension method is below:
public static class Extensions
{
public static IQueryable<T> OrderByPropertyOrField<T>
(this IQueryable<T> queryable, string propertyOrFieldName, bool ascending = true)
{
var elementType = typeof (T);
var orderByMethodName = ascending ? "OrderBy" : "OrderByDescending";
var parameterExpression = Expression.Parameter(elementType);
var propertyOrFieldExpression =
Expression.PropertyOrField(parameterExpression, propertyOrFieldName);
var selector = Expression.Lambda(propertyOrFieldExpression, parameterExpression);
var orderByExpression = Expression.Call(typeof (Queryable), orderByMethodName,
new[] {elementType, propertyOrFieldExpression.Type}, queryable.Expression, selector);
return queryable.Provider.CreateQuery<T>(orderByExpression);
}
}
Download the completed project here.
CodeProject
The post Paging in ASP.NET Web API appeared first on Spencer Schneidenbach.