如何以编程方式连接到IIS中承载的WCF服务

Sta*_*ace 5 c# asp.net-mvc wcf wcf-binding

IIS中托管的WCF服务的绑定和客户端端点如下所示.

<bindings>
    <customBinding>
          <binding name="notSecureBinding">
              <binaryMessageEncoding />
              <httpTransport maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" />
          </binding>
          <binding name="SecureBinding">
              <binaryMessageEncoding />
              <httpsTransport maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" />
          </binding>
      </customBinding>
  </bindings>



<client>
      <endpoint address="http://ServerName.myDomain.org/ADSearcher/Service1.svc"
                binding="customBinding"
                bindingConfiguration="notSecureBinding"
                contract="GetData.GetData"
                name="notSecureBinding" />

      <endpoint address="https://ServerName.myDomain.org/ADSearcher/Service1.svc"
                binding="customBinding"
                bindingConfiguration="SecureBinding"
                contract="GetData.GetData"
                name="SecureBinding" />
  </client>
Run Code Online (Sandbox Code Playgroud)

现在我想做的是连接到这个服务并读取我想要的数据,而不是在我的asp.net mvc 4应用程序中添加任何服务引用.

我在下面尝试了这段代码

BasicHttpBinding basicHttpBinding = new BasicHttpBinding();
EndpointAddress endpointAddress = new EndpointAddress("http://ServerName.myDomain.org/ADSearcher/Service1.svc");
IService1 ADUser = new ChannelFactory<IService1>(basicHttpBinding, endpointAddress).CreateChannel();
DataTable ADUserInfo = ADUser.GetADUserList(strUserName, strFirstName, strLastName, strEmail, domain);
Run Code Online (Sandbox Code Playgroud)

但上面的代码抛出了下面的错误.

由于EndpointDispatcher上的ContractFilter不匹配,因此无法在接收方处理带有Action'http://tempuri.org/IService1/GetADUserList ' 的消息.这可能是由于合同不匹配(发送方与接收方之间的操作不匹配)或发送方与接收方之间的绑定/安全性不匹配.检查发送方和接收方是否具有相同的合同和相同的绑定(包括安全要求,例如消息,传输,无).

它看起来像绑定不匹配,因为在WCF配置中,我使用"customBinding"但我无法在C#代码中定义它,只找到"BasicHttpBinding".

有没有人知道我如何通过C#代码成功连接到这个IIS托管的WCF服务并调用我的"GetADUserList"方法而不向我的MVC应用程序添加服务引用?

小智 0

CustomBinding命名空间中有一个类System.ServiceModel可以使用。

Binding customBinding = new CustomBinding(
             new BinaryMessageEncodingBindingElement(),
             new HttpTransportBindingElement 
             { 
               MaxReceivedMessageSize = 2147483647, 
               MaxBufferSize = 2147483647 
             });
EndpointAddress endpointAddress = new EndpointAddress("http://ServerName.myDomain.org/ADSearcher/Service1.svc");
IService1 ADUser = new ChannelFactory<IService1>(customBinding, endpointAddress).CreateChannel();
Run Code Online (Sandbox Code Playgroud)