ASP.NET Core Web API Interview Question #119

How should dynamic sorting be handled safely?

Dependency Injection, Services, EF Core, Async & Data Access Mid-Level Intermediate

Quick Interview Answer

Map client-supported sort names to known expressions instead of directly injecting arbitrary field names into SQL or accepting unrestricted expressions. Validate the requested direction and use a stable secondary ordering when necessary.

Detailed Explanation

Map client-supported sort names to known expressions instead of directly injecting arbitrary field names into SQL or accepting unrestricted expressions. Validate the requested direction and use a stable secondary ordering when necessary.

A whitelist keeps the public sorting contract explicit and avoids exposing internal database structure.

Code Example

query = sort?.ToLowerInvariant() switch
{
    "price_desc" => query.OrderByDescending(x => x.Price)
                         .ThenBy(x => x.Id),
    "price"      => query.OrderBy(x => x.Price)
                         .ThenBy(x => x.Id),
    _            => query.OrderBy(x => x.Id)
};