title: call a wcf rest service and return data as xml or json
body: <p>I'm trying to get data from a WCF REST service to come back as either xml or json.</p>
  
  <p>I can return data as xml or json when setting the RequestFormat and ResponseFormat using the WebInvoke attribute and setting both to the appropriate format as such:</p>
  
  <p>But I don't want to hardcode the format, so researched it further on the web and I found a couple of things but no matter what I do, it always seems to return my data in xml format.</p>
  
  <p>Here is what I've done:</p>
  
  <ol>
  <li><p>Removed the RequestFormat and ResponseFormat from the WebInvoke attribute.</p>
  
  <pre><code>[OperationContract]
  [WebInvoke(
     Method = "GET",
     RequestFormat = WebMessageFormat.Json,
     ResponseFormat = WebMessageFormat.Json,
     BodyStyle = WebMessageBodyStyle.Wrapped,
     UriTemplate = "Search/{searchName}/{fieldValues}")]
  Result Search(string searchName, string fieldValues);
  </code></pre></li>
  <li><p>I added the following section to my web.config:</p>
  
  <pre><code>&lt;system.serviceModel&gt;
    &lt;standardEndpoints&gt;
      &lt;webHttpEndpoint&gt;
        &lt;standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/&gt;
      &lt;/webHttpEndpoint&gt;
    &lt;/standardEndpoints&gt;
  &lt;/system.serviceModel&gt;
  </code></pre>
  
  <p>I don't know if the above is required since I was able to format in both format without having this in my web.config, but I guess, it does say automaticaFormat</p></li>
  <li><p>When calling <code>WebClient</code>, I set both the <code>Content-Type</code> and <code>Accept</code> headers to <code>application/xml</code> or `application/json.</p>
  
  <p>But even after making these changes and setting my headers to <code>application/json</code>, it still returns the data as XML.</p>
  
  <p>I tried it in Fiddler, but same thing. Request is received, response is returned but in xml.</p></li>
  <li><p>I also tried putting the following code into the calling WCF method, but still no good:</p>
  
  <pre><code>WebOperationContext.Current.OutgoingResponse.ContentType = "application/json";
  </code></pre></li>
  <li><p>Finally, I found this <a href="http://msdn.microsoft.com/en-us/library/ee354381.aspx" rel="nofollow" title="A Developer's Introduction to Windows Communication Foundation 4">article</a> and followed the steps as far as I can tell, but no good once again! Just look for "message format selection section".</p></li>
  </ol>
  
  <p>I'm obviously missing something, but what??? Has anyone got any ideas on how this can be achieved?</p>