【问题标题】:How to return Json from WCF Service?如何从 WCF 服务返回 Json?
【发布时间】:2009-12-02 03:18:02
【问题描述】:

我有下面一段代码,它是支持 Ajax 的模板 WCF 服务。我该怎么做才能让它返回 JSON 而不是 XML? 谢谢。

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;
    }
}

【问题讨论】:

    标签: wcf json


    【解决方案1】:

    你试过了吗:

    [WebGet(ResponseFormat= WebMessageFormat.Json)]
    

    【讨论】:

    • 谢谢。是的,我试过了,但我仍然从 JQuery 代码中得到错误。这是我用来调用服务的代码: var parameters = 7 $.ajax({ type: "POST", url: "localhost:53153/TestWebServiceEightSite/CostService.svc", data: parameters, contentType: "application/json; charset=utf- 8", dataType: "json", 成功: function(result) { $("InputHTML").val(result); }, error: function(e) { alert(e); } });
    【解决方案2】:

    如果您想使用$.ajax({ type: "POST", ...) 中的 POST 动词,您需要使用 [WebInvoke(Method="POST"] 标记您的方法。

    既然你用[WebGet](相当于[WebInvoke(Method="GET")])标记了它,你应该使用GET动词来调用服务,例如:

    $.ajax({ type: "GET", ...) 或使用$.get(url, data, ...)(有关详细信息,请参阅jQuery.get)。

    您需要将 ResponseFormat 设置为 Json,正如 tomasr 已经指出的那样。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-06
      • 2019-05-24
      • 1970-01-01
      • 1970-01-01
      • 2012-01-09
      • 1970-01-01
      • 2012-12-30
      • 1970-01-01
      相关资源
      最近更新 更多