WCF Service . Setting response type to XML/JSON using the Accept HTTP Header?

﹥>﹥吖頭↗ 提交于 2021-02-04 21:07:16

问题


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.

This is my service definition:

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

Im making the request here :

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
}

I know I can make two endpoints and specify one as XML and the other as JSON but id rather not do this.

Any ideas?


回答1:


For that you have on server set a property automaticFormatSelectionEnabled to true

You can do it either in config

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

or in code:

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


来源:https://stackoverflow.com/questions/23057741/wcf-service-setting-response-type-to-xml-json-using-the-accept-http-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!