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:
In order to consume it using jQuery you will need to write the following ajax call:
In regular XmlHttpRequest requests, you will need to set the request headers like in the beforeSend function implementation in the previous code sample.
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.