WCF REST returns a single method like JSON and XML

I am using below code for WCF Rest Services to access 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 also return an XML type. Do I need another method? I want to do this in the same method without duplicating the code for XML. I am using WCF 3.5. I can’t change my version.

+6
wcf
source share
3 answers

I had the same problem. We provided a solution by creating two endpoints for XML, and the other for JSON.

Make sure you remove all attributes from the service interface. Do not specify RequestFormat or ResponseFormat to control XML or JSON. Let it be controlled by the endpoint.

Changes to the Web.Config service.

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

+13
source share

You don’t even need to specify the return type here, we have a property called automaticFormatSelectionEnabled for WebGet in endpoint modes, as shown below. When you make your request for rest from the client, you can specify the type as WebClient.Headers ["Content-type"] = "application / json"; or WebClient.Headers ["Content -type"] = "application / xml"; , the service will determine the type and return the desired format.

  <endpointBehaviors> <behavior name="RestServiceEndPointBehavior"> <webHttp automaticFormatSelectionEnabled="true" /> </behavior> </endpointBehaviors> 
+3
source share

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

For 3.5, you need to do most of the work. This post has an implementation of this particular scenario. You need to create a special implementation for formatting send messages that (probably) wraps two formatting, one for JSON and one for XML. And when serializing the answer, decide which formatter to use based on your logic.

+2
source share

All Articles