Question

I have a web service returning JSON, but now I'd like to modify it to allow callers to specify a callback function so the return goes from: JSON DATA to specifiedFunction(JSON DATA); The way I'm returning JSON right now is just by returning an instance of an object and having .NET do its serialization magic, if I change to just returning a string I can add the name of the function and the brackets around the data but then I end up with quotation marks in the return, because its a string and I don't want those. So how can I go about it?

Reason for this is we want developers calling our API to be able to use the dynamic script tag as explained here http://www.xml.com/pub/a/2005/12/21/json-dynamic-script-tag.html

Was it helpful?

Solution

The technique you are after is called JSONP (JSON with Padding).

See How to support JSONP in WCF services:

The JsonPEncoder is a wrapping encoder on the WCF JSON encoder. It delegates most calls to the wrapped encoder. The WriteMesage methods have been overriden to pad the outgoing message with the callback method. The JsonBehavior is used on the service operation to enable JSONP encoding for that operation. The query parameter of the URI that holds the callback function name is specified as the CallBack property of the behavior.

OTHER TIPS

In WCF 4.0 added support for JSONP. You may use

  <bindings>
    <webHttpBinding>
      <binding name="webHttpBindingWithJsonP" crossDomainScriptAccessEnabled="true" />
    </webHttpBinding>
  </bindings>

http://bendewey.wordpress.com/2009/11/24/using-jsonp-with-wcf-and-jquery/

I don't know what version of HTML they're using, but in all the versions that I've used, the src attribute in a script tag has to be a URL. They're somehow using a function instead, and I don't see that working.

Have you actually seen a dynamic script tag work?

I know it's an old thread, but it seems that everyone insists on changing the WCF to support JSONP when that's clearly not what the poster asked. And I posted here and forums.asp.net and nobody took the time to reply.

I ended up returning it as a stream. This causes the "raw" mode to be used and WCF will not touch the response. Link: http://blogs.msdn.com/b/carlosfigueira/archive/2008/04/17/wcf-raw-programming-model-web.aspx.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top