2013-02-25 28 views
6

我使用下面的代碼爲WCF REST服務以JSON格式WCF REST返回單一方法,JSON和XML

[OperationContract] 

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

我想這個方法也返回XML類型來獲得。我是否需要爲此擁有更多方法? 我想用同樣的方法做到這一點,而不需要重複XML代碼。 我正在使用WCF 3.5。我無法更改我的版本。

回答

3

您甚至不需要在此處指定返回類型,我們有一個名爲automaticFormatSelectionEnabled用於WebGet的終點行爲,如下所示。當您向客戶端發出休息呼叫請求時,您可以指定類型爲WebClient.Headers [「Content-type」] =「application/json」;WebClient.Headers [「Content-type」] =「application/xml」;,服務將檢測類型,並返回你想要的格式正確..

<endpointBehaviors> 
     <behavior name="RestServiceEndPointBehavior"> 
      <webHttp automaticFormatSelectionEnabled="true" /> 
     </behavior> 
    </endpointBehaviors> 
+0

''automaticFormatSelectionEnabled'屬性在.NET 4.0中添加; OP指定他們需要使用3.5 – carlosfigueira 2013-02-25 06:07:33

+1

是的,它是4.0以上..:S。 – 2013-02-25 07:14:32

+0

-1:OP需要.NET 3.5 – 2013-12-23 19:55:42

2

如果您正在使用.NET 4.0或4.5,那麼這將是簡單的 - 無論是使用自動格式選擇通過Vibin Kesavan的建議,或者在操作中根據您的一些邏輯將WebOperationContext.Current.OutgoingResponse.Format設置爲JSON或XML。

對於3.5,您需要完成大部分工作。 This post恰好具有此場景的實現。您需要創建自定義調度消息格式化程序實現(可能)包裝兩個格式化程序,一個用於JSON,另一個用於XML。當序列化響應時,根據您的邏輯決定使用哪個格式化器。

13

我遇到了同樣的問題。 我們通過爲XML創建兩個端點併爲JSON創建兩個端點來提供解決方案。

確保您從服務界面中刪除所有屬性。不要指定RequestFormat或ResponseFormat來控制XML或JSON。讓它由端點控制。

服務Web.Config更改。

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

希望這會有所幫助。

+0

什麼是contract =「xxxxxx.Ixxxxxxx」是那個namespace.Interface? – Demodave 2015-04-02 15:19:10

+1

contract =「xxxxxx.Ixxxxxxx」確實是對接口的引用。 – 2015-12-02 13:54:39

+1

@Satchi這真的有幫助。謝謝。 – 2016-01-25 09:07:06