以编程方式添加端点

pal*_*now 3 wcf wcf-endpoint

我有一个WCF服务,我在客户端应用程序中连接.我在配置文件中使用以下.

<system.serviceModel>  
    <bindings>  
      <basicHttpBinding>  
        <binding name="MyNameSpace.TestService" closeTimeout="00:01:00" openTimeout="00:01:00"  
            receiveTimeout="00:10:00" sendTimeout="00:01:00" allowCookies="false"  
            bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"  
            maxBufferSize="2147483647" maxBufferPoolSize="524288" maxReceivedMessageSize="2147483647"  
            messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"  
            useDefaultWebProxy="true">  
          <readerQuotas maxDepth="32" maxStringContentLength="2147483647" maxArrayLength="16384"  
              maxBytesPerRead="4096" maxNameTableCharCount="16384" />  
          <security mode="None">  
            <transport clientCredentialType="None" proxyCredentialType="None"  
                realm="" />  
            <message clientCredentialType="UserName" algorithmSuite="Default" />  
          </security>  
        </binding>  
      </basicHttpBinding>  
    </bindings>  
    <client>  
      <endpoint address="http://localhost:9100/TestService" binding="basicHttpBinding"  
          bindingConfiguration="MyNameSpace.TestService" contract="TestService.IService" name="MyNameSpace.TestService" />  
    </client>  
</system.serviceModel>  
Run Code Online (Sandbox Code Playgroud)

在代码中,我在此服务上调用API,如下所示,

TestServiceClient client = new TestServiceClient()
client.BlahBlah()
Run Code Online (Sandbox Code Playgroud)

现在我想用porgramatically定义端点.怎么办?我在配置文件中注释掉了部分,因为我认为我必须在TestServiceClient实例上放置一些代码来动态添加端点,然后在实例化TestServiceClient时抛出异常.

无法在ServiceModel客户端配置部分中找到引用合同"TestService.IService"的默认端点元素.这可能是因为没有为您的应用程序找到配置文件,或者因为在客户端元素中找不到与此合同匹配的端点元素.

我怎么能做到这一点?此外,以编程方式添加端点的代码示例的任何一点都将受到赞赏.

Moh*_*and 9

要以编程方式创建端点和绑定,您可以在服务上执行此操作:

ServiceHost _host = new ServiceHost(typeof(TestService), null);

var _basicHttpBinding = new System.ServiceModel.basicHttpBinding();
            //Modify your bindings settings if you wish, for example timeout values
            _basicHttpBinding.OpenTimeout = new TimeSpan(4, 0, 0);
            _basicHttpBinding.CloseTimeout = new TimeSpan(4, 0, 0);
            _host.AddServiceEndpoint(_basicHttpBinding, "http://192.168.1.51/TestService.svc");
            _host.Open();
Run Code Online (Sandbox Code Playgroud)

您还可以在服务配置中定义多个端点,并在运行时选择要动态连接的端点.

在客户端程序上,您将执行此操作:

basicHttpBinding _binding = new basicHttpBinding();
EndpointAddress _endpoint = new EndpointAddress(new Uri("http://192.168.1.51/TestService.svc"));

TestServiceClient _client = new TestServiceClient(_binding, _endpoint);
_client.BlahBlah();
Run Code Online (Sandbox Code Playgroud)