【问题标题】:WCF Service . Setting response type to XML/JSON using the Accept HTTP Header?WCF 服务。使用接受 HTTP 标头将响应类型设置为 XML/JSON?
【发布时间】:2014-04-14 10:26:10
【问题描述】:

我希望我的 WCF 服务接受并响应 JSON 或 XML 格式的请求。 我认为 WCF 应该根据客户端指定的 Accept 标头自动解释响应类型。 但是在我的客户端请求中,我将接受标头指定为 application/json 但我收到了 XML 响应。

这是我的服务定义:

[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "/GetChecks", BodyStyle = WebMessageBodyStyle.Bare)]
Check[] GetChecks(MyCustomObj Object);

我在这里提出请求:

using (WebClient client = new WebClient())
{
    client.Headers["Content-type"] = "application/json";
    client.Headers["Accept"] = "application/json";

    string response = client.UploadString(endpoint, JSONRequestString);   
    // Response is XML
}

我知道我可以创建两个端点并将一个指定为 XML,另一个指定为 JSON,但 id 而不是这样做。

有什么想法吗?

【问题讨论】:

    标签: c# xml json wcf serialization


    【解决方案1】:

    为此,您在服务器上将属性 automaticFormatSelectionEnabled 设置为 true

    你可以在配置中做到这一点

    <webHttpEndpoint> 
        <standardEndpoint name="" helpEnabled="true"  
                                    automaticFormatSelectionEnabled="true"/> 
    </webHttpEndpoint>
    

    或在代码中:

    var host = new ServiceHost(typeof (PricingService));
    var beh = new WebHttpBehavior { AutomaticFormatSelectionEnabled = true };
    host.AddServiceEndpoint(typeof (IPricingService), new WebHttpBinding(), uri)
                .Behaviors.Add(beh);
    

    【讨论】:

      猜你喜欢
      • 2014-11-26
      • 2016-07-11
      • 2022-11-01
      • 2016-06-04
      • 2017-08-08
      • 1970-01-01
      • 2012-06-19
      • 2017-06-16
      • 2017-08-29
      相关资源
      最近更新 更多