gpt4 book ai didi

c# - 如何以编程方式修改 WCF app.config 端点地址设置?

转载 作者:IT王子 更新时间:2023-10-29 03:50:13 25 4
gpt4 key购买 nike

我想以编程方式修改我的 app.config 文件以设置应使用哪个服务文件端点。在运行时执行此操作的最佳方法是什么?供引用:

<endpoint address="http://mydomain/MyService.svc"
binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IASRService"
contract="ASRService.IASRService" name="WSHttpBinding_IASRService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>

最佳答案

这是在客户端吗??

如果是这样,您需要创建一个 WsHttpBinding 实例和一个 EndpointAddress,然后将这两个传递给将这两个作为参数的代理客户端构造函数。

// using System.ServiceModel;
WSHttpBinding binding = new WSHttpBinding();
EndpointAddress endpoint = new EndpointAddress(new Uri("http://localhost:9000/MyService"));

MyServiceClient client = new MyServiceClient(binding, endpoint);

如果它在服务器端,您需要以编程方式创建您自己的 ServiceHost 实例,并向其添加适当的服务端点。

ServiceHost svcHost = new ServiceHost(typeof(MyService), null);

svcHost.AddServiceEndpoint(typeof(IMyService),
new WSHttpBinding(),
"http://localhost:9000/MyService");

当然,您可以将多个这样的服务端点添加到您的服务主机中。完成后,您需要通过调用 .Open() 方法打开服务主机。

如果您希望能够在运行时动态地选择要使用的配置,您可以定义多个配置,每个配置都有一个唯一的名称,然后调用适当的构造函数(为您的服务主机或代理客户端)使用您希望使用的配置名称。

例如你可以很容易地拥有:

<endpoint address="http://mydomain/MyService.svc"
binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IASRService"
contract="ASRService.IASRService"
name="WSHttpBinding_IASRService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>

<endpoint address="https://mydomain/MyService2.svc"
binding="wsHttpBinding" bindingConfiguration="SecureHttpBinding_IASRService"
contract="ASRService.IASRService"
name="SecureWSHttpBinding_IASRService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>

<endpoint address="net.tcp://mydomain/MyService3.svc"
binding="netTcpBinding" bindingConfiguration="NetTcpBinding_IASRService"
contract="ASRService.IASRService"
name="NetTcpBinding_IASRService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>

(三个不同的名称,不同的参数通过指定不同的bindingConfigurations)然后选择正确的一个来实例化你的服务器(或客户端代理)。

但在这两种情况下 - 服务器和客户端 - 您必须在实际创建服务主机或代理客户端之前进行选择。 一旦创建,它们就是不可变的 - 一旦它们启动并运行,您就无法调整它们。

马克

关于c# - 如何以编程方式修改 WCF app.config 端点地址设置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/966323/

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