Over a million developers have joined DZone.

Adding Queryable Support to ASP.NET Web API Controller Action Methods

DZone's Guide to

Adding Queryable Support to ASP.NET Web API Controller Action Methods

Free Resource

Bugsnag monitors application stability, so you can make data-driven decisions on whether you should be building new features, or fixing bugs. Learn more.

In this article I will show that how we can make our Web API methods queryable so the user can apply query operators and expressions to filter data.

We will use OData library for ASP.NET Web API that have the [Queryable] attribute provided, which facilitates in issuing queries.

1. Create ASP.Net Web API Project

2. Add sample model class which defines properties

3. In this example, I have created a Session class as follows


4. Now add a SessionController which will contain Get, Post, Put, Delete methods for CRUD operations.

5. It will create an empty controller. Now we will specify Get method and return session list as queryable.

6. Now add OData reference from Nuget Package Manager by searching as web api odata and click Install on Microsoft ASP.NET Web API 2 OData

7. Once you install, It will ask you to accept the license agreement, click I Accept and proceed

8. Now add [Queryable] attribute on GetSession method.

That’s it, build the solution and test.

9. Open fiddler and select GET HTTP Method and navigate to the URL i.e. http://[youraddress:port]/api/Session


10. Once you hit the above URI it will show you the complete session list in JSON format as follows

11. Now you can apply query operators on your request and filter data

Following are some query operators you can use to issue queries

$top=n: Returns only the first n entities in an entity set (or in Atom terms, the first n entries in a feed).

$skip=n: Skips the first n entities in an entity set. Using this option lets a client retrieve a series of distinct pages on subsequent requests.

$format: Determines whether data should be returned in JSON or the XML-based Atom/AtomPub format. (The default is Atom/AtomPub.)

$orderby=: Orders results, in ascending or descending order, by the value of one or more properties in those results.

$filter=: Returns only entities that match the specified expression.

$select=: Returns only the specified properties in an entity.

$inlinecount: Returns the server computed count of the number of entries produced by the query request.


To select top 2, my URI would be like http://[youraddress;portNo[/api/Session?$top=2



Monitor application stability with Bugsnag to decide if your engineering team should be building new features on your roadmap or fixing bugs to stabilize your application.Try it free.

dotnet ,asp.net ,tips and tricks ,odata ,asp.net web api ,queryable

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}