I'm trying to get data from a WCF REST service to come back as either xml or json.
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:
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.
Here is what I've done:
Removed the RequestFormat and ResponseFormat from the WebInvoke attribute.
[OperationContract] [WebInvoke( Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped, UriTemplate = "Search/{searchName}/{fieldValues}")] Result Search(string searchName, string fieldValues);
I added the following section to my web.config:
<system.serviceModel> <standardEndpoints> <webHttpEndpoint> <standardEndpoint name="" helpEnabled="true" automaticFormatSelectionEnabled="true"/> </webHttpEndpoint> </standardEndpoints> </system.serviceModel>
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
When calling
WebClient
, I set both theContent-Type
andAccept
headers toapplication/xml
or `application/json.But even after making these changes and setting my headers to
application/json
, it still returns the data as XML.I tried it in Fiddler, but same thing. Request is received, response is returned but in xml.
I also tried putting the following code into the calling WCF method, but still no good:
WebOperationContext.Current.OutgoingResponse.ContentType = "application/json";
Finally, I found this article and followed the steps as far as I can tell, but no good once again! Just look for "message format selection section".
I'm obviously missing something, but what??? Has anyone got any ideas on how this can be achieved?
ASP.NET Web API
services have this features built-in. Use that if you can - unless you need something very specific to WCF. – YK1