Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
331 views
in Technique[技术] by (71.8m points)

.net - WCF REST return single method as JSON and XML

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...