Sorting in ASP.NET Core 2.0 Web API

Problem

How to implement sorting in ASP.NET Core Web API.

Solution

Create an empty project, add NuGet package:

  • System.Linq.Dynamic.Core

Update Startup class to add services and middleware for MVC:

Add model to hold sorting data:

Add an extension method to IQueryable:

Add output models (to send data via API):

Add a service and domain model:

Add a controller for the API with service injected via constructor:

Output:

Discussion

Let’s walk through the sample code step-by-step:

  1. Sorting information is usually received via query parameters. The POCO SortingParams simply hold this information and passes to service (or repository).
  2. Service will then sort the data and returns a list.
    1. Linq.Dynamic.Core provides an extension method on IQueryable that accepts sorting expression as a string.
  3. We build our output model MovieOutputModel and return status code 200 (OK). The output model contains list of movies. As discussed in previous post (CRUD) we map the domain model to an output model (MovieInfo in this case).

Note: The sample is a very basic implementation of sorting. You will get a ParseException if the field specified for sorting doesn’t exist on the model. Typically you would either verify field’s existence or catch the exception.

Source Code

GitHub: https://github.com/TahirNaushad/Fiver.Api.Sorting

Leave a Reply