2011-05-11 50 views
2

我已经接管了.NET WCF项目的开发。除此之外,该项目包含3个文件:WCF:为SOAP和JSON实现使用相同的代码?

  • IApi.cs <=定义接口
  • JsonApi.svc.cs <=为JSON
  • SoapApi.svc.cs <=实现接口SOAP

实现接口的两种实现文件几乎是相同的 - 至少在实现这些方法中的所有代码都是相同的。我对WCF编程颇为陌生,但它让我觉得奇怪,我们需要复制代码,只是为了实现JSON和SOAP。

有没有办法将它合并到一个实现中,让框架决定数据是通过SOAP还是JSON来传输?

/卡斯滕

+1

** SOAP **是一种传输协议 - 其对应部分是REST。 ** JSON **是一种数据格式 - 其对应可能是XML。你正在比较苹果肥皂:-)(双关语意思) – 2011-05-11 15:22:52

+0

如果我错了,请纠正我。你是否想从同一服务中返回xml或json? – 2011-05-11 16:07:36

+0

对不起 - 是的,我是混合条款。但我仍然希望我的实现独立于传输协议和数据格式。 – 2011-05-11 19:53:42

回答

4

定义两个端点,与服务实现相同的合同。定义首先使用SOAP,那么第二个使用JSON:

<service name="YourService"> 
    <endpoint address="rest" 
         binding="webHttpBinding" 
         contract="IYourService" 
         behaviorConfiguration="RestBehavior"/> 
    <endpoint address="soap" 
         binding="wsHttpBinding" 
         contract="IYourService"/> 
    <endpoint address="mex" 
         binding="mexHttpBinding" 
         contract="IMetadataExchange"/> 
</service> 
<endpointBehaviors> 
    <behavior name="RestBehavior"> 
     <webHttp/> 
    </behavior> 
</endpointBehaviors> 

这时会出现在http://.../yourservice.svc/soap,另一个端点在http://.../yourservice.svc/rest

[编辑]回答您的意见,我说的是更换本节:

<services> 
    <service name="WebApi.SoapApi" behaviorConfiguration="ApiBehavior"> 
    <endpoint address="basic" bindingNamespace="http://api.myservice.dk/Basic" contract="WebApi.IApi" binding="basicHttpBinding" bindingConfiguration="ApiBinding" /> 
    </service> 
    <service name="WebApi.JsonApi" behaviorConfiguration="ApiBehavior"> 
    <endpoint address="web" bindingNamespace="http://api.myservice.dk/Web" contract="WebApi.IApi" binding="webHttpBinding" bindingConfiguration="ApiBinding" behaviorConfiguration="JsonBehavior" /> 
    </service> 
</services> 

由:

<services> 
    <service name="WebApi.UniqueApi" behaviorConfiguration="ApiBehavior"> 
    <endpoint address="basic" bindingNamespace="http://api.myservice.dk/Basic" contract="WebApi.IApi" binding="basicHttpBinding" bindingConfiguration="ApiBinding" /> 
    <endpoint address="web" bindingNamespace="http://api.myservice.dk/Web" contract="WebApi.IApi" binding="webHttpBinding" bindingConfiguration="ApiBinding" behaviorConfiguration="JsonBehavior" /> 
    </service> 
</services> 

一个服务,带有两个端点

+1

我已经这样做了 - 请参阅http://pastie.org/1892193 – 2011-05-12 08:28:52

+0

@Carsten Gehling:看看我的更新... – 2011-05-12 09:24:05

+0

非常整洁 - 谢谢,正是我所需要的。 :-) – 2011-06-14 12:21:29