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

January 28, 2013

2 comments

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.

Add comment
facebook linkedin twitter email

Leave a Reply

Your email address will not be published.

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

2 comments

  1. Samuel Zuniga VanoyeAugust 12, 2014 ב 20:14

    I follow your instructions and the problem I had in the services response was resolved.
    Thanks a lot.

    Reply