2011-07-23 97 views
2

有沒有簡單的方法讓JSONP爲新的WCF Web API休息服務工作?C#WCF Web API + JSONP

我沒有運氣

<standardEndpoints> 
    <webHttpEndpoint> 
    <standardEndpoint name="" 
         helpEnabled="true" 
         automaticFormatSelectionEnabled="true" 
         defaultOutgoingResponseFormat ="Json" 
         crossDomainScriptAccessEnabled="true"/> 
    </webHttpEndpoint> 
</standardEndpoints> 

回答

1

只是想提供有關JSONP的WCF WebAPI開箱即用支持的更多詳細信息。我有一個很艱難的時期找到這些信息,也許這將幫助別人......

This thread了對WCF CodePlex上具有通過丹尼爾羅斯有關如何使用的WebAPI的描述跨域JSON查詢(又名JSONP)使用jQuery。

他引用的「樣本」可以在WCF CodePlex存儲庫here中找到。它位於「默認」文件夾中。

此外,請確保您使用NuGet安裝預覽版6的WebApiEnhancements,否則這些都不起作用。

你需要一個與Global.asax.cs中像下面...

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

的另一個關鍵是要考慮你的URI模板中的「擴展」 ......

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

然後你讓你的jQuery調用是這樣的...

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