次の方法で共有


Getting JSON Out of WCF Data Services

I was working with Ralph and a few other folks in my team on an internal project that required us to pass an OData feed from our own Windows Azure-hosted WCF Data Service to Windows Azure Marketplace DataMarket. In the process of doing this, I was reminded that, as other’s like Josh Einstein and Chris Love have already blogged about, WCF Data Services doesn’t support the $format query option out of the box. Rather, it basically just ignores it. As such, the data service is designed to only respond with a JSON-formatted response when a request has an Accept header value of application/json. However, because MarketPlace requires that all OData system query options be supported when you bring your own OData data feed, we needed to enable this query option in our data service.

First…some background

The OData protocol supports both JavaScript Notation (JSON) and Atom feeds, and OData  provides the $format system query option to allow a client to request the format of the response feed. This system query option, if supported by the data service, must override the value of the Accept header of the request. The good news is that WCF Data Services does support returning both JSON and Atom feeds. The bad news is that the default implementation does not support the $format query option and uses only the value of the Accept header to determine the format of the response. Since there are cases when your data service may need to support the $format query option, such as when clients can’t set the Accept header or when using JSONP (aka. “JSON with Padding”). To support these scenarios, you must extend your data service to handle this option in the URI.

How do I enable support for $format

To enable this support in WCF Data Services, you need to basically get the incoming request, remove the $format query option from the URI, and then change the Accept header to application/json. Luckily, there is code out their that does this for you in these WCF Data Services extension projects.

You can add this functionality to your data service by downloading one of these projects, adding the code to your WCF Data Services project, and turning it on in one of these ways:

  • JSONP and URL project—when you add the JSONPSupportBehaviorAttribute to your data service class, the the service can handle the $format query option $format=json. In my case, I also further modified this project to also handle $format=atom required by DataMarket.
  • WCF Data Services Toolkit—when your service inherits from the ODataService<T> class included in the WCF Data Services Toolkit project, then your implementation already includes support for both $format=json and JSONP. For more information, see Building Real-World OData Services.

Cheers!

Glenn Gailey