Click here to Skip to main content
13,633,447 members
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

3.6K views
2 bookmarked
Posted 1 Sep 2017
Licenced CPOL

Sorting in ASP.NET Core 2.0 Web API

, 1 Sep 2017
Rate this:
Please Sign up or sign in to vote.
How to implement sorting in ASP.NET Core Web API. Continue reading...

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:

public void ConfigureServices(
            IServiceCollection services)
        {
            services.AddSingleton<IMovieService, MovieService>();

            services.AddMvc();
        }

        public void Configure(
            IApplicationBuilder app,
            IHostingEnvironment env)
        {
            app.UseDeveloperExceptionPage();
            app.UseMvcWithDefaultRoute();
        }

Add model to hold sorting data:

public class SortingParams
    {
        public string SortBy { get; set; } = "";
    }

Add an extension method to IQueryable:

public static IQueryable<T> Sort<T>(this IQueryable<T> source, string sortBy)
        {
            if (source == null)
                throw new ArgumentNullException("source");

            if (string.IsNullOrEmpty(sortBy))
                throw new ArgumentNullException("sortBy");

            source = source.OrderBy(sortBy);

            return source;
        }

Add output models (to send data via API):

public class MovieOutputModel
    {
        public List<MovieInfo> Items { get; set; }
    }

    public class MovieInfo
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public int ReleaseYear { get; set; }
        public string Summary { get; set; }
        public string LeadActor { get; set; }
        public DateTime LastReadAt { get; set; }
    }

Add a service and domain model:

public interface IMovieService
    {
        List<Movie> GetMovies(FilteringParams filteringParams);
    }
    public class MovieService : IMovieService
    {
        public List<Movie> GetMovies(SortingParams sortingParams)
        {
            var query = this.movies.AsQueryable();

            if (!string.IsNullOrEmpty(sortingParams.SortBy))
                query = query.Sort(sortingParams.SortBy);

            return query.ToList();
        }
    }

    public class Movie
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public int ReleaseYear { get; set; }
        public string Summary { get; set; }
        public string LeadActor { get; set; }
    }

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

[Route("movies")]
    public class MoviesController : Controller
    {
        private readonly IMovieService service;

        public MoviesController(IMovieService service)
        {
            this.service = service;
        }

        [HttpGet(Name = "GetMovies")]
        public IActionResult Get(SortingParams sortingParams)
        {
            var model = service.GetMovies(sortingParams);
            
            var outputModel = new MovieOutputModel
            {
                Items = model.Select(m => ToMovieInfo(m)).ToList(),
            };
            return Ok(outputModel);
        }
    }

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 to service (or repository).
  2. Service will then sort the data and returns a list.
    • 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 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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Tahir Naushad
Software Developer (Senior)
United Kingdom United Kingdom
Qualified and skilled professional with experience working as a Software Developer, Technical Lead and Architect. I have worked on windows, web and distributed applications using the latest set of technologies within the Microsoft .NET ecosystem. I have lead teams using agile methodologies and trained developers in writing well-designed and maintainable software applications.

Currently focusing on C#, ASP.NET Core, EF, JavaScript, React, Azure, Domain Driven Design and Microservices.

You may also be interested in...

Comments and Discussions

 
QuestionNice Article ! Pin
Stef Heyenrath16-Jan-18 9:04
memberStef Heyenrath16-Jan-18 9:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01 | 2.8.180712.1 | Last Updated 1 Sep 2017
Article Copyright 2017 by Tahir Naushad
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid