DCSIMG
Why My WCF Data Service isn’t Returning JSON Format? - Gil Fink's Blog

Gil Fink's Blog

Fink about IT

News

Microsoft MVP

My Facebook Profile My Twitter Profile My Linkedin Profile

Locations of visitors to this page

Creative Commons License

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.
© Copyright 2013 Gil Fink

Hebrew Articles

Index Pages

My OSS Projects

English Articles

Why My WCF Data Service isn’t Returning JSON Format?

Why My WCF Data Service isn’t Returning JSON Format?

Why My WCF Data Service isn’t Returning JSON Format?Lately, I had the need to use WCF Data Services in a project. It has been a while since I used and wrote about WCF Data Services and a lot was changed in the framework. The scenario I needed to implement was calling a data service using jQuery. So I wrote the relevant service and used the code I wrote a few years ago and nothing happened… I got a HTTP error – HTTP Error 415 Unsupported media type. Since I know that WCF Data Services support JSON format, I’ve scratch my head and started to investigate what happened.

OData V3 Protocol and JSON

OData V3 protocol, which is implemented in WCF Data Services 5.0, includes a more efficient format for JSON serialization. In order to get the new response format you must explicitly request application/json;odata=verbose or set the MaxDataServiceVersion header to 2.0 (which is the previous protocol version). If you won’t do so you will get the HTTP error 415 result that I got.

So if you have the following WCF Data Service:

public class MyDataService : DataService<EFModel> {
   public static void InitializeService(DataServiceConfiguration config)  {
     config.SetEntitySetAccessRule("*", EntitySetRights.AllRead);
     config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;
   }
}

In order to consume it using jQuery you will need to write the following ajax call:

$.ajax("MyDataService.svc/Entities", {
    dataType: "json", 
    beforeSend: function (xhr) {
        xhr.setRequestHeader("Accept", "application/json;odata=verbose");
        xhr.setRequestHeader("MaxDataServiceVersion", "3.0");
    },
    success: function (data) {
       // do something with the data you got
    },
    error: function (err) {
        console.log(err);
    }
});

In regular XmlHttpRequest requests, you will need to set the request headers like in the beforeSend function implementation in the previous code sample.

Summary

OData V3 protocol changed the way data is JSON serialized. In order to keep backward compatibility with the previous protocol versions, in V3 you need to explicitly set the request headers if you want to get JSON responses from your service. Another option is to appoint the previous protocol version (2.0) in the service configuration.

Comments

No Comments