Search code examples
.netxmlwcfweb-servicesjson

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.


Solution

  • 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.