Filtering In ASP.NET Core 2.0 Web API

Problem

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

Solution

To an empty project update Startup class to add services and middleware for MVC,

  1. public void ConfigureServices(IServiceCollection services)    
  2. {    
  3.       services.AddSingleton<IMovieService, MovieService>();    
  4.     
  5.       services.AddMvc();    
  6. }    
  7.     
  8. public void Configure(IApplicationBuilder app,IHostingEnvironment env)    
  9. {    
  10.       app.UseDeveloperExceptionPage();    
  11.       app.UseMvcWithDefaultRoute();    
  12. } 

Add model to hold filtering data

Add a service and domain model

Add output models (to send data via API)

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

Output


Discussion

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

  1. Filtering information is usually received via query parameters. The POCO FilteringParamssimply hold this information and passes to service (or repository).
  2. Service will then filter the data and returns a list.
  3. We build our output model MovieOutputModel and return status code 200(OK). The output model contains,

    1. Total number of items returned by the server.
    2. List of movies. As discussed in previous post (CRUD) we map the domain model to an output model (MovieInfo in this case).

Source Code

GitHub