开发者

WCF: Using the same code for SOAP and JSON implementation?

开发者 https://www.devze.com 2023-03-05 16:27 出处:网络
I have taken over development on a .NET WCF project. Among other things, the project contains 3 files:

I have taken over development on a .NET WCF project. Among other things, the project contains 3 files:

  • IApi.cs <= Defining the interfaces
  • JsonApi.svc.cs <= Implementing interface for JSON
  • SoapApi.svc.cs <= Implementing interface for SOAP

The two implementation files are almost identical - at least all the code in the implementation of the methods is identical. I am quite new to WCF programming, but it strikes me as odd, that we need to duplicate the code, just to implement JSON as well as SOAP.

Is there a way to merge this into one implementation and let开发者_如何学Python the framework decide if data is to be transported by SOAP or JSON?

/ Carsten


Defines two endpoints, with the same contract for your service implementation. Defines the first to use SOAP, then the second to use 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>

Then there will be an endpoint at http://.../yourservice.svc/soap and another at http://.../yourservice.svc/rest

[edit] to answer to your comment, what I said is to replace this section :

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

by :

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

One service, with two endpoints

0

精彩评论

暂无评论...
验证码 换一张
取 消