C# WCF Web API + JSONP

喜夏-厌秋 提交于 2019-11-28 02:14:54

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!