Friday, June 5, 2015

How to enable OData in Web API

ASP.NET Web API supports OData queries out of the box for all your complex data querying needs using the Web Service. There are just three steps you need to do to implement it. Make sure you install the OData nuget package though first.

1) Use the attribute [EnableQuery()] to decorate the targeted Web API end point

2) Make sure you return IQueryable (not IEnumerable or any other variant) from the REST end point

3) Add AsQueryable() at the end of your LINQ query so it can return the items as IQueryable.

Example:

[EnableQuery()]
public IQueryable<Order> Get()
{
    return orderRepository.Retrieve().AsQueryable();
}


And that's it. You can skip, sort, take, filter and do all the things you need to shape your queries for returning your data to your UI in the manner you like. Of course, you need to use the OData query syntax from your UI code to hit the endpoints. All in all, a very simple API to learn and implement, rather than trying to roll out your own custom filtering, sorting et al code.

No comments:

Post a Comment