简体   繁体   中英

call a wcf rest service and return data as xml or json

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:

  1. 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);
  2. 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

  3. When calling WebClient , I set both the Content-Type and Accept headers to application/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.

  4. I also tried putting the following code into the calling WCF method, but still no good:

     WebOperationContext.Current.OutgoingResponse.ContentType = "application/json";
  5. 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?

What you are requesting is something I actually achieved today. I needed to create a RESTful service providing either JSON or XML in return. It is a bit domain specific, but if your read between the lines the following blog shows how to achieve this by means of a MemoryStream return type:

http://www.j4jayant.com/articles/fhir/22-fhir-feel-2

In the GetResourceFeed function, you can see how the Accept value in the request is used to switch between JSON and XML (atom). Please feel free to try it out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM