如何从WCF服务返回Json ?

时间:2022-10-18 14:16:12

I have the piece of code below of a template Ajax enabled WCF service. What can i do to make it return JSon instead of XML? thanks.

我有一个模板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;
    }
}

2 个解决方案

#1


7  

Have you tried:

你有试过:

[WebGet(ResponseFormat= WebMessageFormat.Json)]

#2


1  

If you want to use the POST verb as in $.ajax({ type: "POST", ...) you will need to markup your method with [WebInvoke(Method="POST"].

如果您想使用POST谓词,如$。ajax({类型:“POST”,…)您将需要使用[WebInvoke(方法="POST")标记方法。

Since you marked it up with [WebGet] (which is equivalent to [WebInvoke(Method="GET")]) you should call the service using the GET verb, e.g.:

由于您使用[WebGet](相当于[WebInvoke(Method="GET")])进行标记,因此您应该使用GET谓词调用服务,例如:

$.ajax({ type: "GET", ...) or use $.get(url, data, ...) (see jQuery.get for more info).

美元。ajax({类型:“GET”,…)或使用$。获取(url,数据,…)(参见jQuery。获得更多信息)。

And you'll need to set the ResponseFormat to Json, as tomasr already pointed out.

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

#1


7  

Have you tried:

你有试过:

[WebGet(ResponseFormat= WebMessageFormat.Json)]

#2


1  

If you want to use the POST verb as in $.ajax({ type: "POST", ...) you will need to markup your method with [WebInvoke(Method="POST"].

如果您想使用POST谓词,如$。ajax({类型:“POST”,…)您将需要使用[WebInvoke(方法="POST")标记方法。

Since you marked it up with [WebGet] (which is equivalent to [WebInvoke(Method="GET")]) you should call the service using the GET verb, e.g.:

由于您使用[WebGet](相当于[WebInvoke(Method="GET")])进行标记,因此您应该使用GET谓词调用服务,例如:

$.ajax({ type: "GET", ...) or use $.get(url, data, ...) (see jQuery.get for more info).

美元。ajax({类型:“GET”,…)或使用$。获取(url,数据,…)(参见jQuery。获得更多信息)。

And you'll need to set the ResponseFormat to Json, as tomasr already pointed out.

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