CathalMF
CathalMF

Reputation: 10055

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

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?

Upvotes: 1

Views: 3276

Answers (1)

Igor Tkachenko
Igor Tkachenko

Reputation: 1120

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);

Upvotes: 3

Related Questions