WCF服务.使用“接受HTTP标头"将响应类型设置为XML/JSON?
我希望我的WCF服务接受并响应JSON或XML的请求. 我认为WCF应该根据客户端指定的Accept标头自动解释响应类型. 但是,在我的客户请求中,我将accept标头指定为application/json,但是我收到了XML响应.
I want my WCF service to accept and respond to requests in JSON or XML. I thought that WCF was supposed to automatically interpret the response type based on the Accept header that the client specifies. However in my client request I specify the accept header to be application/json but I receive an XML response.
这是我的服务定义:
[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却不这样做.
I know I can make two endpoints and specify one as XML and the other as JSON but id rather not do this.
有什么想法吗?
为此,您需要在服务器上将属性automaticFormatSelectionEnabled设置为true
For that you have on server set a property automaticFormatSelectionEnabled to true
您可以在config中完成
You can do it either in config
<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);