gpt4 book ai didi

wcf - 以编程方式添加端点

转载 作者:行者123 更新时间:2023-12-04 15:47:05 29 4
gpt4 key购买 nike

我有一个在客户端应用程序中连接的 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()

现在我想以编程方式定义端点。怎么可能呢?我从配置文件中注释掉了部分,因为我想我必须在 TestServiceClient 实例上放置一些代码来动态添加端点,但是它会在 TestServiceClient 实例化的地方引发以下异常。

Could not find default endpoint element that references contract 'TestService.IService' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element.

我怎样才能做到这一点?此外,任何关于以编程方式添加端点的代码示例的点都将不胜感激。

最佳答案

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

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

关于wcf - 以编程方式添加端点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11583882/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com