2009-12-02 145 views
9

我有一個模板Ajax啓用WCF服務下面的代碼段。我能做些什麼來使它返回JSon而不是XML? 謝謝。如何從WCF服務返回Json?

using System; 
using System.Linq; 
using System.Runtime.Serialization; 
using System.ServiceModel; 
using System.ServiceModel.Activation; 

[ServiceContract(Namespace = "WCFServiceEight")] 
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] 
public class CostService 
{ 
    // Add [WebGet] attribute to use HTTP GET 
    [OperationContract] 
    [WebGet] 
    public double CostOfSandwiches(int quantity) 
    { 
     return 1.25 * quantity; 
    } 
} 

回答

7

你試過:

[WebGet(ResponseFormat= WebMessageFormat.Json)] 
+0

謝謝。 是的,我嘗試過,但我仍然從JQuery代碼中得到錯誤。這裏是我正在使用的代碼來調用服務: var parameters = 7 $ .ajax({type:「POST」, url:「http:// localhost:53153/TestWebServiceEightSite/CostService.svc」, 數據:參數, 的contentType: 「應用程序/ JSON;字符集= UTF-8」, 數據類型: 「JSON」, 成功:功能(結果){。 $( 「InputHTML」)VAL(結果); } , error:function(e){ alert(e); } }); – Zinoo 2009-12-02 03:48:32

+0

你看過:http://www.west-wind.com/weblog/posts/324917.aspx? – tomasr 2009-12-02 03:51:38

1

如果你想使用POST謂詞在$.ajax({ type: "POST", ...)你將需要[WebInvoke(Method="POST"]來標記你的方法。

既然你[WebGet](這相當於[WebInvoke(Method="GET")]),標誌着它應該叫使用GET動詞

$.ajax({ type: "GET", ...)服務,例如:或使用$.get(url, data, ...)(見jQuery.get獲取更多信息)。

而且您需要將ResponseFormat設置爲Json,因爲tomasr已經指出。