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.
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:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplication15.Models
{
public class Employee
public int id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
Step 3
Now add an API Controller to the project as in the following:
Add the following code:
using System.Net;
using System.Net.Http;
using System.Web.Http;
using WebApplication15.Models;
namespace WebApplication15.Controllers
public class EmployeesController : ApiController
public IQueryable<Employee> GetEmployee()
List<Employee> list = new List<Employee>();
list.Add(new Employee { id = 1, Name = "Name1", Address = "Address1" });
list.Add(new Employee { id = 2, Name = "Name2", Address = "Address2" });
list.Add(new Employee { id = 3, Name = "Name3", Address = "Address3" });
list.Add(new Employee { id = 4, Name = "Name4", Address = "Address4" });
list.Add(new Employee { id = 5, Name = "Name5", Address = "Address5" });
list.Add(new Employee { id = 6, Name = "Name6", Address = "Address6" });
return list.AsQueryable();
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:
[Queryable]
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".
Select Top 2 record "http://localhost:42095/api/employees?$top=2".
Skip the starting 2 record "http://localhost:42095/api/employees?$skip=3".
ASP.NET MVC 5: A Beginner’s Guide