c# - 为 WCF 编写编程配置更改时遇到问题

标签 c# wcf config

我需要能够以编程方式更新我的配置文件并更改我的 WCF 设置。我一直在尝试使用我在网上找到的一些示例在一些测试代码中执行此操作,但无法获取配置文件来反射(reflect)端点地址的更改。

配置(片段):

  <!-- Sync Support -->
  <service   name="Server.ServerImpl"
             behaviorConfiguration="syncServiceBehavior">

    <host>
      <baseAddresses>
        <add baseAddress="http://localhost:8000/SyncServerHarness"/>
      </baseAddresses>
    </host>

    <endpoint name="syncEndPoint" 
              address="http://localhost:8000/SyncServerHarness/Sync"
              binding="basicHttpBinding"
              contract="Server.IServer" />

    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />

  </service>

代码:

Configuration config = ConfigurationManager.OpenExeConfiguration
                       (ConfigurationUserLevel.None);

ServiceModelSectionGroup section = (ServiceModelSectionGroup)
                                   config.SectionGroups["system.serviceModel"];

foreach (ServiceElement svc in section.Services.Services)
{
   foreach (ServiceEndpointElement ep in svc.Endpoints)
   {
       if (ep.Name == "syncEndPoint")
       {
          ep.Address = new Uri("http://192.168.0.1:8000/whateverService");

       }
   }
}

config.Save(ConfigurationSaveMode.Full);
ConfigurationManager.RefreshSection("system.serviceModel");

此代码执行时没有异常,但没有进行任何更改。此外,我在索引端点和服务时也遇到了麻烦。有没有简单的方法可以找到它?使用 name 作为索引器似乎不起作用。

谢谢!

齐格

最佳答案

我改变了两件事,它对我来说效果很好:

1) 我正在使用OpenExeConfiguration与装配路径

2) 我正在访问 <services>部分,而不是 <system.serviceModel>部分组

通过这两项更改,一切正常:

Configuration config = ConfigurationManager.OpenExeConfiguration
                       (Assembly.GetExecutingAssembly().Location);

ServicesSection section = config.GetSection("system.serviceModel/services") 
                             as ServicesSection;

foreach (ServiceElement svc in section.Services)
{
   foreach (ServiceEndpointElement ep in svc.Endpoints)
   {
       if (ep.Name == "syncEndPoint")
       {
          ep.Address = new Uri("http://192.168.0.1:8000/whateverService");
       }
   }
}

config.Save(ConfigurationSaveMode.Full);

关于c# - 为 WCF 编写编程配置更改时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2380697/

相关文章:

c# - 如何取消选择列表框中的单个项目

WCF 读取数据成员名称属性

ios - XML 错误 : Unquoted attribute value

php - Laravel 5 - 配置子文件夹

wcf - 如何更改azure平台和/或模拟器中的机器配置中的超时?

c# - 每次选中一项时如何触发Selected事件

c# - Windows 8 Metro App 制作设置弹出窗口

c# - linq to sql where子句有什么不同

c# - 如何让WCF服务使用HTTPS协议(protocol)

c# - 使工作角色的多个实例执行相同工作的推荐方法是什么?