问题
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