9
votes

I am using below Code for WCF Rest Services to get in JSON format

[OperationContract]   

[WebGet(UriTemplate = "/GetOrderList?request={request}", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
IEnumerable<Order> GetOrderList(Request request);

I want this method to return XML type also. Do i need to have one more method for it ? I want to do it in the same method without duplicating the code for XML. I am using WCF 3.5. I cannot change my version.

3

3 Answers

20
votes

I was having the same issue. We provided the solution by creating two endpoints one for XML and the other for JSON.

Make sure you remove all attributes from the Service Interface. Don't specify the RequestFormat or ResponseFormat to control XML or JSON. Let it be controlled by the endpoint.

Service Web.Config changes.

<endpoint address="XML" binding="webHttpBinding" bindingConfiguration="webHttpBindingXML" contract="xxxxxx.Ixxxxxxx" behaviorConfiguration="RestXMLEndpointBehavior"/>
<endpoint address="JSON" binding="webHttpBinding" bindingConfiguration="webHttpBindingJSON" contract="xxxxxxxx.Ixxxxxxxxx" behaviorConfiguration="RestJSONEndpointBehavior"/>
  <endpointBehaviors>

    <behavior name="RestJSONEndpointBehavior">
      <webHttp helpEnabled="true" defaultOutgoingResponseFormat="Json"/>
    </behavior>
    <behavior name="RestXMLEndpointBehavior">
      <webHttp helpEnabled="true" defaultOutgoingResponseFormat="Xml"/>
    </behavior>

  </endpointBehaviors>        
<webHttpBinding>
<binding name="webHttpBindingXML"/>
<binding name="webHttpBindingJSON"/>
</webHttpBinding>

Hope this helps.

7
votes

You don't even need to specify the return type here , we have a property called automaticFormatSelectionEnabled for WebGet in end point behaviors as shown below. When you making your rest call request from client, you can specify the type as WebClient.Headers["Content-type"] = "application/json"; or WebClient.Headers["Content-type"] = "application/xml"; , service will detect the type and return the correct format you want ..

  <endpointBehaviors>
        <behavior name="RestServiceEndPointBehavior">
          <webHttp automaticFormatSelectionEnabled="true"   />
        </behavior>
  </endpointBehaviors>
3
votes

If you were using .NET 4.0 or 4.5, then it would be simple - either use the automatic format selection as suggested by Vibin Kesavan, or within the operation set the WebOperationContext.Current.OutgoingResponse.Format to either JSON or XML depending on some of your logic.

For 3.5, you need to do most of the work. This post has an implementation exactly of this scenario. You need to create a custom dispatch message formatter implementation which (likely) wraps two formatters, one for JSON and one for XML. And when serializing the response, decide which formatter to use based on your logic.