Friday, February 22, 2013

Self hosted ASP.Net Web API OData service

In my previous post I showed how to create ASP.Net Web API OData application. In this post I'll show, how to host an ASP.Net Web API OData service in a console application.

First create a console application using .net 4.5. Add two nuget packages, which are

  • Microsoft.AspNet.WebApi.Selfhost
  • Microsoft.AspNet.WebApi.OData
Create a new model class called Student.
Also create StudentFacade class like below. 
First we have to write our EDM model. To do that add a new method to Program class like below. 
Using ODataConventionModelBuilder, we define which entity sets that should be exposed to the out side world. 
Now we have to configure our OData route.  MapODataRoute is an extension method. We have to add using staement for System.Web.Http.OData. Since we are going to do a self hosted service, we have to use HttpSelfHostConfiguration class for the OData configuration.
Now we have to create a sever and host the service in there.
Below is the Program class up to now.
Now run the application and go to http://localhost:53543/odata/ using browser. You can see the service document for this particular service. 
To view other metadata of the service, access the http://localhost:53543/odata/$metadata URL. 
Now we need to access Student data set. Go to  http://localhost:53543/odata/student URL. But you'll get 404 message.
Reason is though you have exposed the entity sets, there must be an ODataController to expose data from entity sets.
We have to define an ODataController like below.
Run the program again and go to  http://localhost:53543/odata/student URL. You'll see a list of students.

No comments:

Post a Comment