Thursday, February 21, 2013

OData using ASP.Net Web API

OData is a data access protocol in the web. This OData protocol supports for both XML and JSON formats.

In this post I'll explain how to create an OData end point using ASP.Net web API.

Create ASP.net mvc application using .net 4.5. Install Microsoft.AspNet.WebApi.OData nuget package.
Create a model class called Student.
Build the solution and add StudentController to the project. Add code like below.
Open App_Start folder and edit WebApiConfig.cs file to configure the OData end points. Add the following code.
ODataConventionModelBuilder needs to know the collections that we need to expose to the outside world. So we are configuring that in here.
In above code "Student" is name of the entityset. Name of the controller must match the name of the entityset. Particular end point can have multiple entity sets.
The first parameter is the route name. The second parameter is the URI prefix for the endpoint. Then for the Student entityset the URI is http:/hostname/odata/Student. For an application there can be more than one OData endpoint. After we run the code, the results would be look like below.

Pagination using OData Web API

Using OData Web API, we can have server driven paging. The only thing that we have to do is pass PageSize argument for QueryableAttribute.
After that the results will be look like below.
In JSON result there's a new thing called odata.nextLink. Using that we can fetch the next page.

2 comments:

  1. Wow Great Article. Good Work. it would be really great if you can add one example with Odata where close filter.


    Cheers!!
    Akash

    ReplyDelete
    Replies
    1. Thank you Prabath aiyya. Sure, I'll do it ASAP. :)

      Delete