Here is how we can use the OData query Option in ASP.Net Web API.
What are OData Query options? There can be a requirement wherein a client sends some parameters in the request URI and those parameters are applied on the server side to perform the desired actions while getting data from API service interface.
Here are the various parameters that can be used together with API URI in request.
- $expand
- $filter
- $inlinecount
- $orderby
- $select
- $skip
- $top
Here are the examples of some the most used parameter with web API URI.
- http://localhost/api/Employees?$expand=DeptId
- http://localhost/api/Employees?$filter=Id ge 5 and Price le 15
- http://localhost/api/Employees?$inlinecount=allpages
- http://localhost/api/Employees?$orderby=Id desc
- http://localhost/api/Employees?$select=EmployeeName, Salary
- http://localhost/api/Employees?$skip=10
- http://localhost/api/Employees?$top=5
Now to implement support for OData Query Options we have to do a few things listed down here.
- Install package 'Microsoft.AspNet.WebApi.OData.5.7.0'
- Enable support for OData query options in Web API Configuration class.
- public static class WebApiConfig
- {
- public static void Register(HttpConfiguration config)
- {
- config.EnableQuerySupport();
- // Web API routes
- //config.MapHttpAttributeRoutes();
- config.Routes.MapHttpRoute(
- name: "DefaultApi",
- routeTemplate: "Api/{controller}/{id}",
- defaults: new { id = RouteParameter.Optional }
- );
- }
- }
This setting will enable OData Query Support at global level.
But If we want to enable OData query support for only one controller method then we call apply [Queryable] attribute to the controller action.
- [Queryable]
- public IEnumerable<string> Get()
- {
- return new string[] { "value1", "value2" };
- }
Once that’s done then we start using query option in our API calls.
Limiting Query Options
With OData query options come to a feature called “limiting query option” with that we can put a limit on what type of query option can be used while calling a certain API action.
Here are some of the examples of how we can use limitation on query options.
- [Queryable (AllowedQueryOptions=AllowedQueryOptions.Top | AllowedQueryOptions.Skip)] - This will limit usage to only top and skip.
- [Queryable (AllowedOrderByProperties="Id")] - we can use comma separated property name like Id, EmployeeName etc
- [Queryable (AllowedLogicalOperators=AllowedLogicalOperators.Equal)] - This will limit usage to only equal.

Seemo AliPosted May 14, 2020, 6:13 PM
I attempted to create validation on filter, but I can not do validation on all properties, the validation ( ValidateSingleValuePropertyAccessNode ) is per each property, any idea how solve this ?
Hiten PandyaPosted Nov 28, 2018, 11:18 PM
Thank you so much sir for sharing your knowledge.
Rushi MehtaPosted Nov 28, 2018, 9:08 PM
Thanks for sharing the article