Question

Is there an easy way to get JSONP working for the new WCF Web API rest services?

I've tried this with no luck

<standardEndpoints>
  <webHttpEndpoint>
    <standardEndpoint name=""
                      helpEnabled="true"
                      automaticFormatSelectionEnabled="true"
                      defaultOutgoingResponseFormat ="Json"
                      crossDomainScriptAccessEnabled="true"/>
  </webHttpEndpoint>
</standardEndpoints>
Was it helpful?

Solution

https://alexanderzeitler.com/articles/Look-Ma,-I-can-handle-JSONP-%28aka-Cross-Domain-JSON%29-with-WCF-Web-API-and-jQuery!/

Update: Latest WCF Web API bits ships with integrated JSONP support whereas usage is almost similar to the way described in the link above.

OTHER TIPS

You may checkout the following blog post for using JSONP with WCF in .NET 4.0.

Just wanted to provide more detail on WCF WebAPI out-of-the-box support for JSONP. I had a really hard time finding this information, so perhaps it will help somebody else...

This thread over on the WCF CodePlex has a description by Daniel Roth about how to use WebApi cross-domain JSON queries (a.k.a JSONP) using jQuery.

The "sample" he references can be found in the WCF CodePlex repository here. It is in the "default" folder.

Also, make sure you install the WebApiEnhancements for Preview 6 using NuGet otherwise none of this will work.

You'll need a Global.asax.cs with something like the following...

public class Global : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        var config = new WebApiConfiguration() { EnableTestClient = true };
        RouteTable.Routes.MapServiceRoute<HelloWorldApi>("api", config);
    }
}

The other key is to account for an "extension" in your URI template...

[WebGet(UriTemplate="hello{ext}")]

Then you make your jQuery call like this...

$.getJSON("/api/hello.jsonp?callback=?", function (data) {
    $("div").html(data);
}); 

Here's another blog post that describes how to add a JsonpFormatter to a project.

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