Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return JSON wrapped in a callback function from a WCF REST web service

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

like image 201
Michael Behan Avatar asked Jul 24 '09 16:07

Michael Behan


3 Answers

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.

like image 77
Crescent Fresh Avatar answered Sep 30 '22 22:09

Crescent Fresh


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/

like image 34
GreenGood Avatar answered Sep 30 '22 22:09

GreenGood


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?

like image 36
John Saunders Avatar answered Oct 01 '22 00:10

John Saunders