WCF REST返回单一的方法,JSON和XML方法、REST、WCF、JSON

2023-09-03 07:55:21 作者:对着成绩单唱忐忑

我使用跌破$ C $下WCF REST服务得到JSON格式

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);

我想这个方法返回的XML类型也。我需要有一个方法呢? 我想这样做在同一个方法,无需复制code为XML。 我使用WCF 3.5。我不能改变我的版本。

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.

推荐答案

我有同样的问题。 我们通过创建两个端点一个用于XML和其他对JSON提供的解决方案。

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

请确保你的服务接口删除所有属性。不要指定RequestFormat或ResponseFormat控制XML或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.

服务Web.Config变化。

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.