RESTful WCF service that can respond in both JSON(P) and XML and still be used as SOAP web service?

StackOverflow https://stackoverflow.com/questions/607767

  •  03-07-2019
  •  | 
  •  

Question

Given a contract such as:

[ServiceContract] public interface IService
{
    [OperationContract]
    [WebGet(UriTemplate = "GetData/{id}.{format}")]
    ResponseData GetData(string id, string format);
}

Is there a way to get the service to respond with json when requested as: /GetData/1234.json, xml when requested as /GetData/1234.xml and still be available as a proper soap service at some other url, with a strongly typed wsdl contract?

Using a Stream as the return value for GetData is not workable, as though it fufills the first two requirements, wcf can't create a full wsdl specification as it has no idea what the contents of the resultant Stream will be.

Was it helpful?

Solution

You should have two separate methods which take id and format (and they would call a shared implementation that returns ResponseData) which have different WebGet attributes:

[ServiceContract]
public interface IService
{
    [OperationContract]
    [WebGet(UriTemplate = "GetData/{id}.{format}.xml", 
        ResponseFormat=WebMessageFormat.Xml)]
    ResponseData GetDataXml(string id, string format);

    [OperationContract]
    [WebGet(UriTemplate = "GetData/{id}.{format}.json", 
        ResponseFormat=WebMessageFormat.Json)]
    ResponseData GetDataJson(string id, string format);
}

For the SOAP endpoint, you should be able to call either method, but you are going to have to have a separate ServiceHost instance hosting the implementation of the contract.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top