【发布时间】:2011-11-20 16:28:37
【问题描述】:
我刚刚创建了我的第一个 WCF REST 服务。我希望它返回 JSON,所以我指定了响应格式。一开始我很沮丧,因为它一直在返回 SOAP,我不知道为什么,但是我看到一个博主在使用 Fiddler,所以我尝试了它,然后我得到了 JSON 响应。
我认为原因是因为 Fiddler 没有发送这个 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)
标签: wcf json http rest wcf-rest