Introduction

This article explains how to use the Query Operators in Web API2 for filtering the data. For this we need to make the Web API method a Queryable method. Here we use the OData library that provides the [Queryable] attribute to the ASP.NET Web API2.

The following are the various query methods that we can use in the Web API:

Use the following procedure to create the Web API application.

Step 1

Create the application using the following:

Step 2

Now add the Model Class:

Add the following simple lines of code:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. namespace WebApplication15.Models
  6. {
  7. public class Employee
  8. {
  9. public int id { get; set; }
  10. public string Name { get; set; }
  11. public string Address { get; set; }
  12. }
  13. }

Step 3

Now add an API Controller to the project as in the following:

Add the following code:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Net.Http;
  6. using System.Web.Http;
  7. using WebApplication15.Models;
  8. namespace WebApplication15.Controllers
  9. {
  10. public class EmployeesController : ApiController
  11. {
  12. public IQueryable<Employee> GetEmployee()
  13. {
  14. List<Employee> list = new List<Employee>();
  15. list.Add(new Employee { id = 1, Name = "Name1", Address = "Address1" });
  16. list.Add(new Employee { id = 2, Name = "Name2", Address = "Address2" });
  17. list.Add(new Employee { id = 3, Name = "Name3", Address = "Address3" });
  18. list.Add(new Employee { id = 4, Name = "Name4", Address = "Address4" });
  19. list.Add(new Employee { id = 5, Name = "Name5", Address = "Address5" });
  20. list.Add(new Employee { id = 6, Name = "Name6", Address = "Address6" });
  21. return list.AsQueryable();
  22. }
  23. }
  24. }

Step 4

Now install the Web API2 OData 5.0.0 package using the following:

Now we add the [Queryable] attribute to the EmployeesController as in the following:

  1. [Queryable]
  2. public IQueryable<Employee> GetEmployee()

Step 5

Now execute the application and copy the URL. Now open the foddle2 tool, paste the copied URL into fiddle and navigate to the existing URL: "http://localhost:42095/api/employees".

Get All Values

Select Top 2 record "http://localhost:42095/api/employees?$top=2".

Select top2 record

Skip the starting 2 record "http://localhost:42095/api/employees?$skip=3".

Skip starting 3 record