Introduction
A product listing endpoint may look simple at first: retrieve products from the database and return them as JSON. In a real application, however, clients rarely want every product. They may need products from a specific category, within a price range, currently in stock, or created after a particular date. They also need to sort results by price, name, or creation date and search within product names and descriptions.
In this lesson, we will improve a GET /api/products endpoint by combining filtering, sorting, and searching with pagination. The goal is to avoid creating a separate endpoint for every combination of requirements and instead build a safe, composable query that is executed by the database.
Core principle: Keep the query as IQueryable for as long as possible and execute it only when the results are actually needed.
1. Designing the query-string contract
Let us define a clear and predictable query-string contract for the listing endpoint:
GET /api/products?categoryId=3&minPrice=100&maxPrice=750&inStock=true&search=keyboard&sortBy=price&sortDirection=desc&createdFrom=2026-01-01&page=2&pageSize=20
Each filter can be optional. When a parameter is not supplied, its filter should not be applied. Pagination, sorting, and maximum page size should still have safe defaults.
Instead of binding query-string values directly to an entity, define a separate request model. This keeps the API contract independent from the database model and provides a central place for validation rules.
public sealed class ProductQueryParameters { public int? CategoryId { get; init; } public decimal? MinPrice { get; init; } public decimal? MaxPrice { get; init; } public bool? InStock { get; init; } public DateTimeOffset? CreatedFrom { get; init; } public DateTimeOffset? CreatedTo { get; init; } public string? Search { get; init; } public string? SortBy { get; init; } public string? SortDirection { get; init; } public int Page { get; init; } = 1; public int PageSize { get; init; } = 20; }
ASP.NET Core can bind action parameters or properties marked with [FromQuery] from the query string. With ApiController, invalid type conversions can also be turned into appropriate automatic error responses.
2. Applying filters step by step
Start with a queryable base query. Because a listing operation does not modify entities, AsNoTracking avoids unnecessary change-tracking overhead.
public IQueryable<Product> BuildProductQuery(ProductQueryParameters parameters) { IQueryable<Product> query = _db.Products .AsNoTracking() .Where(product => product.IsActive); if (parameters.CategoryId.HasValue) { query = query.Where(product => product.CategoryId == parameters.CategoryId.Value); } if (parameters.MinPrice.HasValue) { query = query.Where(product => product.Price >= parameters.MinPrice.Value); } if (parameters.MaxPrice.HasValue) { query = query.Where(product => product.Price <= parameters.MaxPrice.Value); } if (parameters.InStock.HasValue) { query = parameters.InStock.Value ? query.Where(product => product.StockQuantity > 0) : query.Where(product => product.StockQuantity == 0); } if (parameters.CreatedFrom.HasValue) { query = query.Where(product => product.CreatedAt >= parameters.CreatedFrom.Value); } if (parameters.CreatedTo.HasValue) { query = query.Where(product => product.CreatedAt < parameters.CreatedTo.Value); } if (!string.IsNullOrWhiteSpace(parameters.Search)) { var term = parameters.Search.Trim(); query = query.Where(product => product.Name.Contains(term) || product.Description.Contains(term)); } return query; }
Each Where call builds another query expression; the database has not been contacted yet. The query is executed only when a terminal operation such as CountAsync or ToListAsync is called. This deferred execution makes it possible to compose several optional filters.
Defining date boundaries clearly
Using a less-than comparison for createdTo is often safer. For example, when the client sends 2026-03-01, you may interpret it as “before the beginning of March 1.” For an even clearer contract, you could name the parameter createdToExclusive. Dates should be transported in UTC or with an explicit offset so clients in different time zones receive consistent results.
3. Safe sorting
It is unsafe to turn a user-provided sort field directly into dynamic SQL. It also makes the API contract unclear if clients can sort by every entity property. Instead, explicitly map a small set of allowed fields with a switch expression.
private static IQueryable<Product> ApplySorting( IQueryable<Product> query, ProductQueryParameters parameters) { var descending = string.Equals( parameters.SortDirection, "desc", StringComparison.OrdinalIgnoreCase); return parameters.SortBy?.ToLowerInvariant() switch { "name" => descending ? query.OrderByDescending(product => product.Name) : query.OrderBy(product => product.Name), "price" => descending ? query.OrderByDescending(product => product.Price) : query.OrderBy(product => product.Price), "stock" => descending ? query.OrderByDescending(product => product.StockQuantity) : query.OrderBy(product => product.StockQuantity), "createdat" => descending ? query.OrderByDescending(product => product.CreatedAt) : query.OrderBy(product => product.CreatedAt), _ => query .OrderByDescending(product => product.CreatedAt) .ThenBy(product => product.Id) }; }
Adding Id as a secondary sort in the default ordering is important. When multiple products have the same CreatedAt value, their order is no longer left to a single non-unique column. This makes paginated results more predictable and reduces records moving between pages.
4. Combining the query with pagination
After filtering and sorting, apply projection and pagination. A common approach is to retrieve the total count first and then request only the selected page.
public async Task<PagedResult<ProductListItemDto>> GetProductsAsync( ProductQueryParameters parameters, CancellationToken cancellationToken) { var query = BuildProductQuery(parameters); query = ApplySorting(query, parameters); var totalCount = await query.CountAsync(cancellationToken); var items = await query .Skip((parameters.Page - 1) * parameters.PageSize) .Take(parameters.PageSize) .Select(product => new ProductListItemDto { Id = product.Id, Name = product.Name, Price = product.Price, InStock = product.StockQuantity > 0, CategoryName = product.Category.Name }) .ToListAsync(cancellationToken); return new PagedResult<ProductListItemDto>( items, parameters.Page, parameters.PageSize, totalCount); }
Apply Select as part of the database query rather than loading entities first and projecting in memory. This selects only the columns required by the listing screen. In many listing scenarios, projection is more controlled than loading complete related graphs with Include.
Page must be at least 1, and PageSize should be constrained, for example, between 1 and 100. Otherwise, a client could request an extremely large page and create unnecessary database and memory pressure.
if (parameters.Page < 1) throw new ArgumentOutOfRangeException(nameof(parameters.Page)); if (parameters.PageSize is < 1 or > 100) throw new ArgumentOutOfRangeException(nameof(parameters.PageSize)); if (parameters.MinPrice.HasValue && parameters.MaxPrice.HasValue && parameters.MinPrice > parameters.MaxPrice) { throw new ArgumentException("minPrice cannot be greater than maxPrice."); }
5. The controller layer
The controller should remain thin. It only needs to receive query parameters, pass them to the application layer, and convert the result into an HTTP response.
[ApiController] [Route("api/products")] public sealed class ProductsController : ControllerBase { [HttpGet] [ProducesResponseType(typeof(PagedResult<ProductListItemDto>), StatusCodes.Status200OK)] public async Task<ActionResult<PagedResult<ProductListItemDto>>> GetAll( [FromQuery] ProductQueryParameters parameters, CancellationToken cancellationToken) { var result = await _productService.GetProductsAsync( parameters, cancellationToken); return Ok(result); } }
An example request might look like this:
GET /api/products?search=wireless&inStock=true&sortBy=price&sortDirection=asc&page=1&pageSize=10
Including metadata such as total count, current page, page size, and total pages helps clients plan their next requests and render pagination controls.
6. Performance and database behavior
Using IQueryable alone does not guarantee good performance. The query must be translatable to the database, only necessary columns should be selected, and appropriate indexes should exist. Keep filtering, sorting, and pagination before ToListAsync; operations such as Where or OrderBy after ToList run in memory.
- Good: query.Where(...).OrderBy(...).Skip(...).Take(...).ToListAsync()
- Risky: loading every product with ToListAsync() and filtering in C#.
- Good: projecting the required fields with Select.
- Risky: loading a large entity graph and unnecessary relationships with Include.
Contains is convenient for searching, but searches that begin with a wildcard may not use indexes efficiently. For large catalogs, consider full-text search, a dedicated search system, or database-specific indexing strategies. Make this decision using measurements and actual query plans.
During development, you can inspect generated SQL with ToQueryString(). This output is intended for debugging and should not be treated as SQL that your application executes directly.
Common mistakes
- Accepting arbitrary sort fields: Do not use user input directly as a property name or raw SQL fragment.
- Filtering in memory: Do not call ToListAsync earlier than necessary.
- Using no deterministic ordering: Add a secondary sort for equal values, especially when paginating.
- Leaving PageSize unlimited: Large responses can cause timeouts and memory problems.
- Accepting invalid ranges: Validate negative prices, minPrice > maxPrice, and invalid date ranges.
- Returning entities directly: Use DTOs and projections for list responses.
Short practice exercise
Extend the existing product endpoint with the following requirements:
- Add brand and minStock filters.
- Add name, price, and createdAt to the allowed sort fields.
- Make the default order newest products first, followed by Id.
- Require search to contain at least two characters, or skip the search filter for shorter values.
- Inspect the generated SQL for at least three query-string requests and verify that pagination is performed by the database.
Conclusion
A professional listing endpoint is more than an action that returns data. Its query-string contract, safe sorting, validation, DTO projection, pagination, and database performance must be designed together. By conditionally adding filters and keeping the query as IQueryable, one composable endpoint can support many client requirements.
The next step is to expose this behavior clearly in the API contract, document query parameters in Swagger/OpenAPI, and measure query performance as listing requirements become more complex.
Sources
- https://learn.microsoft.com/en-us/aspnet/core/mvc/models/model-binding?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/ef/core/querying/how-query-works
- https://learn.microsoft.com/en-us/ef/core/performance/efficient-querying
- https://learn.microsoft.com/en-us/ef/core/querying/async
- https://learn.microsoft.com/en-us/aspnet/core/web-api/action-return-types?view=aspnetcore-10.0