是否可以将WCF服务设置为REST& SOAP这种方式?

时间:2011-06-20 15:11:23

标签: c# wcf rest soap

我试图将SOAP和REST结合在一起,进行一些修改。但我不知道它是否可能。我的代码如下,它只用于REST时,但由于我试图将额外的Web服务添加为SOAP(使用配置),它不起作用。不知道如何配置它......

我有接口:

[ServiceContract]
public interface IVLSContentServiceREST
{
    [OperationContract]
    [WebGet]
    string EchoWithGet(string s);

    [OperationContract]
    [WebInvoke]
    string EchoWithPost(string s);

}

[ServiceContract]
public interface IVLSContentServiceSOAP
{
    [OperationContract]
    [WebGet]
    string EchoWithGet(string s);

    [OperationContract]
    [WebInvoke]
    string EchoWithPost(string s);
}

然后我有一个名为VLSContentService.svc的文件:

<%@ ServiceHost Language="C#" Debug="true" Service="VLSContentService" CodeBehind="VLSContentService.svc.cs" %>

和cs(codebehind)文件:

public class VLSContentService : IVLSContentServiceSOAP, IVLSContentServiceREST
{

    string IVLSContentServiceSOAP.EchoWithGet(string s)
    {
        return "You said " + s;
    }

    string IVLSContentServiceSOAP.EchoWithPost(string s)
    {
        return "You said " + s;
    }


    string IVLSContentServiceREST.EchoWithGet(string s)
    {
        return "You said " + s;
    }

    string IVLSContentServiceREST.EchoWithPost(string s)
    {
        return "You said " + s;
    }

}

配置:

<?xml version="1.0"?>
<configuration>

    <system.web>
        <compilation debug="true" targetFramework="4.0" />
    </system.web>

  <system.serviceModel>

    <!---Add the service-->
    <services>
      <service behaviorConfiguration="VLSContentServiceBehaviour" name="VLSContentService">
        <endpoint address="rest" behaviorConfiguration="VLSContentServiceEndpointBehaviour" binding="webHttpBinding" contract="IVLSContentServiceREST"/>
        <endpoint address="soap" behaviorConfiguration="VLSContentServiceEndpointBehaviour" binding="basicHttpBinding" contract="IVLSContentServiceSOAP"/>
      </service>
    </services>

    <!---Add the behaviours-->
    <behaviors>
      <serviceBehaviors>
        <behavior name="VLSContentServiceBehaviour">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>


      <!---Add the behaviours-->
      <endpointBehaviors>
        <behavior name="VLSContentServiceEndpointBehaviour">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>

  </system.serviceModel>
</configuration>

1 个答案:

答案 0 :(得分:3)

您不需要两个版本的合同 - 只需使用不同的绑定在两个端点上托管相同的合同

 <services>
  <service behaviorConfiguration="VLSContentServiceBehaviour" name="VLSContentService">
    <endpoint address="rest" behaviorConfiguration="VLSContentServiceEndpointBehaviour" binding="webHttpBinding" contract="IVLSContentService"/>
    <endpoint address="soap" behaviorConfiguration="VLSContentServiceEndpointBehaviour" binding="basicHttpBinding" contract="IVLSContentService"/>
  </service>
</services>