6
votes

I am consuming odata service using DataServiceContext and want to return data in json format.

I am looking something like this: Odata Query with DataServiceContext and get result as json

If I try to add any request header in the sending request event. I can't see that header in fiddler. Although the event is firing which I have confirmed.

I came across "context.Format.usejson" and try to search it but didn't find anything which I can understand. Can somebody help me please ? Using ODataLib to call a WCF Data Services service operation and JSON

My goal is to consume to OData Service and get result in JSON format using DataServiceContext.

2

2 Answers

11
votes

Note: These steps only work if max protocol version of your service is 3 or higher. Version 3 of OData introduced a new JSON format, and the WCF Data Services client only supports this JSON format. (Old JSON payloads have things like "__metadata" at the top and "d":{...}. In the new JSON format, you'll see things like "odata.metadata", "odata.type", etc.)

First, make sure you have version 5.1 or greater of the WCF Data Sevrices client library (Visual Studio ships with an older version) and an updated version of the tooling that makes "Add Service Reference" in Visual Studio work.

You can download the latest tools installer here: http://www.microsoft.com/en-us/download/details.aspx?id=35840.

Once you've installed that, I recommend upgrading to the latest version of the WCF Data Services client by issuing the following command in the NuGet package manager console:

Install-Package Microsoft.Data.Services.Client

Once you've upgraded to the latest client library, you should be able to use JSON in the client without a problem. Right click on your project in Visual Studio, select "Add Service Reference" and enter the URL of the metadata document of the service. In v5.1 and above, this will pull down the full model of the service, which is needed to support JSON.

"Add Service Reference" will auto-generate a subclass of DataServiceContext. (You can see this generated code by selecting "Show All Files" in the solution explorer of Visual Studio and expanding the code behind the service reference.) For example, when I do "Add Service Reference" against http://services.odata.org/V3/OData/OData.svc/$metadata, the client library generates a class called DemoService. Use that derived class instead of DataServiceContext directly, and you can just call .Format.UseJson(). For example:

var context = new DemoService(new Uri("http://services.odata.org/V3/OData/OData.svc");
context.Format.UseJson();
3
votes

You can call context.Format.UseJson method without providing a parameter if you load your service model inside OnContextCreated partial method as shown in the code below:

public partial class DemoService
{
    partial void OnContextCreated()
    {
        this.Format.LoadServiceModel = GeneratedEdmModel.GetInstance;
    }
}