9

以下のWCF Rest Servicesのコードを使用して、JSON形式で取得しています

[OperationContract]   

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

このメソッドが XML 型も返すようにします。もう1つの方法が必要ですか? XML用のコードを複製せずに同じ方法で行いたいです。WCF 3.5 を使用しています。バージョンを変更できません。

4

3 に答える 3

20

私は同じ問題を抱えていました。XML 用と JSON 用の 2 つのエンドポイントを作成することで、ソリューションを提供しました。

Service Interface からすべての属性を必ず削除してください。XML または JSON を制御するために RequestFormat または ResponseFormat を指定しないでください。エンドポイントで制御できるようにします。

サービス 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>

お役に立てれば。

于 2013-12-23T19:22:14.207 に答える
7

ここで戻り値の型を指定する必要さえありません。以下に示すように、エンドポイント動作の WebGet にはautomaticFormatSelectionEnabledというプロパティがあります。クライアントから残りの呼び出しをリクエストする場合、タイプをWebClient.Headers["Content-type"] = "application/json";として指定できます 。またはWebClient.Headers["Content-type"] = "application/xml"; 、サービスはタイプを検出し、必要な正しい形式を返します..

  <endpointBehaviors>
        <behavior name="RestServiceEndPointBehavior">
          <webHttp automaticFormatSelectionEnabled="true"   />
        </behavior>
  </endpointBehaviors>
于 2013-02-25T05:24:59.117 に答える
3

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.

于 2013-02-25T06:23:19.250 に答える