Using JSONP with WCF and jQuery

In the new release of .NET 4, the WCF team has added support for JSONP.  There are many resource out on the internet about the need for JSONP, if you are reading this article I’m assuming your familar with the concept of JSONP.  Essentially, JSONP utilitzes the <script /> tag as a work around to the cross domain access limitations of web browsers.  This new feature is exposed as an CrossDomainScriptAccessEnabled setting on the WebHttpBinding, and as such is configurable through code or through configuration.

Download

The full source code is available for download from my website

This code requires the latest download of .NET 4 Beta 2 with Visual Studio 2010

Example

In this example we are returning a list of sample customers.  In a standard JSON service using the WebHttpBinding you would recieve this result:

http://localhost:65025/CustomersService.svc/GetCustomers

[{"Email":"bob@example.com","Name":"Bob"},
{"Email":"mark@example.com","Name":"Mark"},
{"Email":"john@example.com","Name":"John"}]

Now using the same service you can supply the optional callback parameter like this http://localhost:65025/CustomersService.svc/GetCustomers?callback=JsonpCallback, which would return the results as the first argument to a function call with a name equal to the one supplied in the query parameter.

JsonpCallback([{"Email":"bob@example.com","Name":"Bob"},
{"Email":"mark@example.com","Name":"Mark"},
{"Email":"john@example.com","Name":"John"}])

So, if you have a javascript function setup on the page, the function will be called successfully without violating the cross-site scripting exceptions.


function JsonpCallback(customers) {
     alert(cutomers.length);
}

WCF Service with CrossDomainScriptAccessEnabled

Creating the WCF Service with CrossDomainScriptAccessEnabled is the same as it would be for any other web enabled WCF service.  In our example we are exposing a simple CustomersService

[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class CustomersService
{
    [OperationContract]
    [WebGet(ResponseFormat = WebMessageFormat.Json)]
    public List GetCustomers()
    {
        return Customer.GetSampleData().ToList();
    }
}

The new JSONP feature is exposed via the WebHttpBinding.  The configuration for the CustomersService would looks like this:

<system.serviceModel>
  <behaviors>
    <endpointBehaviors>
      <behavior name="webHttpBehavior">
        <webHttp />
      </behavior>
    </endpointBehaviors>
  </behaviors>
  <bindings>
    <webHttpBinding>
      <binding name="webHttpBindingWithJsonP" crossDomainScriptAccessEnabled="true" />
    </webHttpBinding>
  </bindings>
  <services>
    <service name="ServiceSite.CustomersService">
      <endpoint address="" binding="webHttpBinding"
                bindingConfiguration="webHttpBindingWithJsonP"
                contract="ServiceSite.CustomersService"
                behaviorConfiguration="webHttpBehavior"/>
    </service>
  </services>
</system.serviceModel>

Notice that we’ve created a new bindingConfiguration for webHttpBindingWithJsonP, in this new binding configuration we’ve set the new property of crossDomainScriptAccessEnabled to true.  This enables the new callback parameter and under the covers attaches the JavascriptCallbackMessageInspector.  I’ve choosen to explicitly setup my binding configuration, but it should be noted that .NET 4 has created default configuration features, a sample of this is available for download with the WCF Samples for .NET 4 Beta2.

Consuming JSONP with jQuery

Now, consuming this JSONP endpoint with jQuery couldn’t be easier.  jQuery ships with an ajax convenience function called getJSON that accepts a url, data, and a callback function.  In the url property you can provide a ? following a query parameter and the ajax function will replace it with a dynamic function to handle the JSONP callback.  With that being said this is what the code to access the customers would look like.

// Get the JsonP data
$.getJSON('http://localhost:65025/CustomersService.svc/GetCustomers?callback=?', null, function (customers) {
    alert('Received ' + customers.length + ' Customers');
});

Conclusion

Many of the code samples above use an abridged version of the code in the sample, so for more detail you should download the source code above.  Additionally this article and samples are based on the .NET 4 Beta 2 product.  I’ll do my best to update the code and ensure everything is in order with the official release.

About these ads

30 Responses to “Using JSONP with WCF and jQuery”


  1. 1 Inge Henriksen May 16, 2010 at 3:59 pm

    Just what I was looking for, thanks!

  2. 2 ramesh shrestha October 4, 2010 at 12:19 pm

    awesome post, you save my days.

  3. 3 Toraj January 10, 2011 at 3:45 pm

    Hi:
    This is a great code clip and article. Thanks for the publication. A great help.
    Toraj

  4. 4 Davyde February 4, 2011 at 8:20 pm

    Can you give some pointers on how to translate the options into a self hosted version, say in the deployment below:

    using (WebServiceHost serviceHost = new WebServiceHost(typeof(FactorNamesService), baseAddress))
    {
    WebHttpBinding whb = new WebHttpBinding();
    whb.CrossDomainScriptAccessEnabled = true;

    serviceHost.AddServiceEndpoint(typeof(INameListService), whb, “”);

    serviceHost.Open();
    Console.WriteLine(“Press to terminate service”);
    Console.ReadLine();
    serviceHost.Close();
    }

  5. 5 Tomcat April 10, 2011 at 10:18 pm

    haha,very good!Thanks

  6. 6 Jon Ivar Nielsen April 22, 2011 at 12:56 pm

    Thanks, Ben.

    Just what I was looking for.

  7. 7 Luan June 6, 2011 at 5:28 am

    Great work Ben! Yours is the only sample I found which works!

  8. 8 Marcel Veldhuizen June 17, 2011 at 10:13 am

    Short and sweet post :)

    I was trying this myself with the final release of .NET 4.0, but I was having no luck: crossDomainScriptAccessEnabled was apparently ignored altogether and regular JSON was being returned.

    It took me a while to spot a difference: in analogy with your example, my endpoint address read “CustomersService.svc” instead of having the empty address like in your configuration. I got rid of it, and that did the trick.

  9. 9 Manfrid June 24, 2011 at 12:49 am

    this code is ok ,but if i want pass some params in url to server,405 not allowed happened.l

  10. 10 Arsalan July 28, 2011 at 2:16 am

    Thanks a lot for your excellent post, i have been messing with cross domain WCF Service Calling, and no other post could clearly explain the stpes involved. And ur code is the only code which i found successfully running. Two thumbs up

  11. 11 Sandesh October 11, 2011 at 2:12 pm

    Thank you very much for this helpful post and code sample

  12. 12 dyardy October 26, 2011 at 7:20 am

    The sample you provided works very well HOWEVER when I try to host on windows 7 iis the server service just doesn’t return anything and in fact if I try to navigate to the svc file I get the following..

    “Security settings for this service require ‘Anonymous’ Authentication but it is not enabled for the IIS application that hosts this service.”

    Any ideas on how to make this sample work while hosted in iis?

    thx

  13. 13 Maxim October 29, 2011 at 3:54 am

    Big thanks for the post, Ben! Helped me a lot!

  14. 14 Dean January 6, 2012 at 4:42 am

    I have been searching for this simple answer for days…

    Thanks!!!

  15. 15 Elz March 23, 2012 at 10:05 am

    I just have one question: what was the reason for not adding a mex endpoint to your service?

  16. 16 bendewey March 23, 2012 at 4:13 pm

    This is a REST endpoint that returns JSON data. WSDL can’t be generated for this type of endpoint. Can I ask the opposite question, why do you need a MEX endpoint?

  17. 17 ram kumar gandhapuneni June 1, 2012 at 2:13 am

    Thanks for the blog post man, it saved me from a day’s worth of research

  18. 18 joffin July 18, 2012 at 1:06 am

    finally i got a working example awesome dude!

  19. 19 Ashraf September 20, 2012 at 2:46 pm

    Great Help, I became stupid to see that the getJSON was not working in firefox. Thank you for the blog post.

  20. 20 Sharad December 20, 2012 at 4:38 am

    gr8 Post, finally i’ve overcome the cross domain issue. :)
    thanks a lot!!!!

  21. 21 vinod k dalakoti January 11, 2013 at 12:05 am

    got the solutions which worked in all browser IE , Firefox, Goggle Chrome

  22. 22 Martin February 20, 2013 at 4:19 am

    your post helped me a lot, big thanks

  23. 23 daemce February 21, 2013 at 5:25 am

    Dude, that is an awesome post. I’ve been struggling with jsonp ajax call for few hours now and you saved me from further agony.
    Thanks a lot!

  24. 24 Jim Rogers March 19, 2013 at 10:33 am

    Awesome, you got me most of the way there, after a couple hours of fruitless research. Just wanted to add that in addition to the code you posted, I needed this in my tag in the config:

    Thanks so much!

  25. 25 Jim Rogers March 19, 2013 at 10:35 am

    Doh! Your comments don’t like XML tags.

    authentication mode=”None”

    …is what’s needed in the system.web tag

  26. 26 Dusan May 21, 2013 at 8:50 am

    finally an up to date release about a microsoft product :)

  27. 27 Vaibhav Singh August 22, 2013 at 12:40 am

    This worked! Thanks for the post!

  28. 28 Pointer September 26, 2013 at 3:37 am

    Love you man’ saved a lot of time


  1. 1 Wonderful Wednesday at { null != Steve } Trackback on November 25, 2009 at 2:29 pm
  2. 2 Jsonp and WCF -Kevin's Mocha Trackback on October 22, 2012 at 4:55 pm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




What else am I doing?

StackOverflow Facebook Twitter LinkedIn Live

Twitter

Pages

November 2009
M T W T F S S
« Aug   Feb »
 1
2345678
9101112131415
16171819202122
23242526272829
30  

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: