Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning JSON AND XML format from a .NET 3.5 WCF web service (REST)

I have an existing web service that returns XML responses and I would like to add some new methods that return JSON. Do I have to create a separate web service that returns in JSON or can I have a mix?

If I use the ResponseFormat = WebMessageFormat.JSON I need to have the service annotated with [DataContractFormat] but I cant seem to have that and [XmlSerializerFormat] which is required for the xml type response format.

like image 445
Michael Behan Avatar asked Oct 15 '22 15:10

Michael Behan


1 Answers

I don't see why this isn't possible. You annotate the service with the [ServiceContract] attribute (not DataContractFormat). It should look like

 [ServiceContract]
    public interface IDoStuff
    {
        [OperationContract]
        [WebInvoke(Method = "POST",
             UriTemplate = "DoStuff",
             ResponseFormat = WebMessageFormat.Json,
             RequestFormat = WebMessageFormat.Json)]
        TestObj DoWork(TestInputObj Inp);
    }

To make it xml, just change the responseformat. When you do your post command, you'll get json, a separate method with the xml format would give you xml.

like image 152
Steve Avatar answered Oct 28 '22 20:10

Steve