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

标签 c# wcf app-config configuration-files

我想以编程方式修改我的 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/

相关文章:

c# - Entity Framework 核心错误?

c# - 如何安装 OpenType(文件类型 : otf) Font on Application Start using C#

c# - 模型方法绑定(bind)在 xaml 中不起作用

.net - 具有 peertrust 和自签名客户端证书的 WCF 传输安全性

wcf - WCF 中的最大数组长度配额异常

mysql - Visual Studio 设置文件损坏/MySQL 连接问题

c# - 为什么调用不同的号码会抛出栈溢出异常?

c# - 告诉 ConfigurationManager 忽略 App.config 部分

从网络共享运行NET4.0应用程序时在app.config中指定defaultProxy时发生异常

WCF:传入消息使用不同于用于加密正文的 token 进行签名。这是意料之中的