2012-07-20 104 views
3

我有一个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> 

在代码中,我对这个服务调用API如下,

TestServiceClient client = new TestServiceClient() 
client.BlahBlah() 

现在我想定义端点porgramatically。如何做到这一点?我从配置文件中注释掉了一部分,因为我想我将不得不在TestServiceClient实例上添加一些代码来动态添加端点,但随后会在TestServiceClient实例化的位置抛出以下异常。

找不到引用合同 “TestService.IService”在ServiceModel客户端配置 栏目默认终结点元素。这可能是因为没有为您的应用程序找到配置文件 ,或者因为在客户端元素中找不到与此 合同匹配的端点元素。

我该如何做到这一点?此外,以编程方式添加端点的代码示例上的任何点都将被赞赏。

回答

8

以编程方式创建端点和绑定,你可以做到这一点的服务:

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(); 

你也可以定义你的服务配置多个端点,并选择动态连接在运行时哪一个。

在客户端程序,然后你可以这样做:

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(); 
0

你可以试试:

TestServiceClient client = new TestServiceClient("MyNameSpace.TestService") 
client.BlahBlah() 

如果不重新检查的命名空间中的文件TestService的是正确的?

1

可你只需要使用:

TestServiceClient client = new TestServiceClient(); 
client.Endpoint.Address = new EndPointAddress("http://someurl"); 
client.BlahBlah(); 

请注意,您绑定配置将不再适用,因为你不使用你的配置文件端点配置。你也必须重写这个。