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 the Startup class to add services and middleware for MVC.

Add model to hold the sorting data.

Add an extension method to IQueryable.

Add output models to send the 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 pass it to the service (or repository).

  2. Service will, then, sort the data and return a list.

    1. Linq.Dynamic.Core provides an extension method on IQueryable that accepts the sorting expression as a string.

  3. We build our output model MovieOutputModel and return the status code 200 (OK). The output model contains a list of movies. As discussed in the 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