【问题标题】:How WCF decides when return SOAP or JSON depending on the request?WCF 如何根据请求决定何时返回 SOAP 或 JSON?
【发布时间】: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


【解决方案1】:

我有这样的端点行为

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

如果您将其配置为端点行为,则无需接触操作合同,并且如果通过不同的端点访问它们,它们会产生不同的输出。

我还不能完全确定的一件事是关于 WCF 似乎产生的两种不同的 Json 样式。如果你使用 enableWebScript 这将产生 { "d" : { ... } } Json 格式,将 defaultOutgoingResponseFormat 选项设置为 Json 将没有 d-object,而只有 Json。

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 我已经更新了帖子。这是 WCF REST 模板附带的示例代码,仅此而已:p
    【解决方案3】:

    您是否尝试过将服务配置设置为使用 webHttpBinding?

    Expose webHttpBinding endpoint in a WCF service

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-18
      • 1970-01-01
      相关资源
      最近更新 更多