2011-09-20 66 views
1

我刚刚创建了我的第一个WCF REST服务。我希望它返回JSON,所以我指定了响应格式。起初,我很沮丧,因为它始终都在返回SOAP,我不知道为什么,但是我看到一个博主使用Fiddler,所以我尝试了它,然后得到了一个JSON响应。WCF如何根据请求决定何时返回SOAP或JSON?

我认为原因是因为提琴手不发送这个HTTP标头:

Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 

但后来我试着用这个标题来制定一个请求:

Accept: application/json,text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 

但事与愿违工作。 WCF如何决定何时使用JSON或SOAP?

有没有办法强制总是返回JSON?

我想确保当我使用服务时,它将返回JSON而不是SOAP。

谢谢。

更新:示例代码:

[ServiceContract] 
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)] 
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)] 
public class Service1 
{ 
    [WebGet(UriTemplate = "", ResponseFormat = WebMessageFormat.Json, RequestFormat= WebMessageFormat.Json)] 
    public List<SampleItem> GetCollection() 
    { 
     // TODO: Replace the current implementation to return a collection of SampleItem instances 
     return new List<SampleItem>() { new SampleItem() { Id = 1, StringValue = "Hello" } }; 
    } 

    [WebInvoke(UriTemplate = "", Method = "POST")] 
    public SampleItem Create(SampleItem instance) 
    { 
     // TODO: Add the new instance of SampleItem to the collection 
     throw new NotImplementedException(); 
    } 

    [WebGet(UriTemplate = "{id}", ResponseFormat = WebMessageFormat.Json)] 
    public SampleItem Get(string id) 
    { 
     // TODO: Return the instance of SampleItem with the given id 
     return new SampleItem() { Id = Int32.Parse(id), StringValue = "Hello" }; 
    } 
} 
+1

您不能返回SOAP - SOAP是呼叫** **协议 - 而不是**数据格式**(如JSON或XML) –

回答

2

我有这样

<endpointBehaviors> 
    <behavior name="jsonEndpoint"> 
    <webHttp defaultOutgoingResponseFormat="Json" /> 
    </behavior> 
</endpointBehaviors> 

的终结点行为如果配置此,你不需要触摸你的业务合同的终结点行为,如果他们”,他们可以产生不同的输出通过不同的端点重新访问。

我还没有完全确定的一件事是关于WCF似乎产生的两种不同的Json风格。如果您使用enableWebScript,则会生成{“d”:{...}} Json格式,并且将defaultOutgoingResponseFormat选项设置为Json,则不会有d对象,而只是Json。

1

我需要看看你的代码,以了解究竟你在做什么。但在这里快速检查。您是否将以下属性应用于您的服务定义?

[System.ServiceModel.Web.WebGet(ResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json)]

+0

我已经更新了文章。它是WCF REST模板附带的示例代码,没有别的:p – vtortola