-
Notifications
You must be signed in to change notification settings - Fork 2
Home
Welcome to the Net.Http.WebApi.OData wiki!
Net.Http.WebApi.OData is a C# library which parses an OData query uri into an object model which can be used to query custom data sources which are not IQueryable
. It was extracted from the MicroLite.Extensions.WebApi library into a separate project so that it could be easily used by other projects.
To use it in your own Web API, firstly install the nuget package Install-Package Net.Http.WebApi.OData
and then in your controller, define a Get method which accepts a single parameter of ODataQueryOptions
:
public IEnumerable<MyClass> Get(ODataQueryOptions queryOptions)
{
// Implement query logic.
}
The ODataQueryOptions
contains properties which can be interrogated to understand the specified query.
Consider the following OData query:
http://localhost/api/Customers?$select=FirstName,LastName,DateOfBirth&$orderby=LastName desc,FirstName
The ODataQueryOptions.Select
would be as follows:
queryOptions.Select.RawValue; // "$select=FirstName,LastName,DateOfBirth"
queryOptions.Select.Properties.Count; // 3
queryOptions.Select.Properties[0]; // "FirstName"
queryOptions.Select.Properties[1]; // "LastName"
queryOptions.Select.Properties[2]; // "DateOfBirth"
The ODataQueryOptions.OrderBy
would be as follows:
queryOptions.OrderBy.RawValue; // "$orderby=LastName desc,FirstName"
queryOptions.OrderBy.Properties.Count; // 2
queryOptions.OrderBy.Properties[0].Direction; // OrderByDirection.Descending
queryOptions.OrderBy.Properties[0].Name; // LastName
queryOptions.OrderBy.Properties[0].RawValue; // "LastName desc"
queryOptions.OrderBy.Properties[1].Direction; // OrderByDirection.Ascending
queryOptions.OrderBy.Properties[1].Name; // FirstName
queryOptions.OrderBy.Properties[1].RawValue; // "FirstName"