WCF服务.使用“接受HTTP标头"将响应类型设置为XML/JSON? [英] WCF Service . Setting response type to XML/JSON using the Accept HTTP Header?

查看:102
本文介绍了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);

这篇关于WCF服务.使用“接受HTTP标头"将响应类型设置为XML/JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆