我刚刚创建了我的第一个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" };
}
}
您不能返回SOAP - SOAP是呼叫** **协议 - 而不是**数据格式**(如JSON或XML) –