OData $format system query option causes Bad Request 400
I have a very simple Reflection-based OData sample the runs fine and generates json 开发者_开发问答when I use the Accept header as indicated. However, I cannot get it to work with the $format=json parameter. Whenever I add that parameter, I get Bad Request. According to this, it seems like it should work: link text
Note that other system query options like $select do work okay. This is .Net 4 running via VS2010.
Using $format=json
out of the box against a .NET 4 WCF Data Service will not work even though the OData Spec says it's supported. I'm not sure exactly why Microsoft does not support it directly. But there are two workarounds to this situation - one feels a little hacky, and the other makes some sense.
First, the solution that feels a little hacky is to build an HttpHandler that intercepts your request, reads the $format=json
querystring parameter and then adds an accepts header to your request (while removing the offending $format=json
parameter). This is described in this blog post.
The second solution, which sounds a little better, is to decorate your data service with a [JSONPSupportBehavior]
attribute. This makes a little more sense and is a little easier to implement (since you don't have to build an HttpHandler). Here are some useful links:
- Blog post describing how to use it.
- Link to download the source code for the
[JSONPSupportBehavior]
attribute (yes, you'll have to build it -- I haven't found a compiled download).
I like the attribute approach, I just wish it wasn't a download off CodePlex...it just doesn't sound that supported yet. But that's just my opinion.
Honestly, if you have control, the best approach is just to add an accepts header to your request of application/json
, and your service will automatically return JSON formatted results.
I hope this helps.
Anyone who comes across this... You can now use WCF Data Services Toolkit and inherit from ODataService rather than DataService to automatically enable this functionality.
精彩评论