tags:

views:

24

answers:

1

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.

+1  A: 

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.

David Hoerster
Thanks for the links--I googled this to death and never found those. I didn't realize $format was reserved which explains the 400. Am I missing a setting that would show me those errors?
JSONPSupportBehavior looks good--a bit more code than one might want but it looks like a useful tool to know how to use.
I see the error in Google Chrome - I didn't really test for the error message in IE or FF. Maybe turn customErrors `mode=Off` in your web.config? Or run it through Fiddler and you should see the error message. Glad this helps!
David Hoerster