2

I need to be able to update my config file programmatically and change my WCF settings. I've been trying to do this inside of some test code using some of the examples I found on the web but so have not been able to get the config file to reflect a change to an endpoint address.

Config (snippet):

  <!-- 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>

Code:

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

This code executes with no exceptions but no changes are made. Also I had trouble indexing the endpoints and services. Is there an easy way to find it? Using name as the indexer did not seem to work.

Thanks!

Sieg

4

2 回答 2

2

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

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);
于 2010-03-04T17:31:39.540 回答
1

以防万一...如果您在调用 RefreshSection 方法后没有更新app.config有一些奇怪的魔力,请确保您没有像在原始帖子中那样调用它:

ConfigurationManager.RefreshSection("system.serviceModel");

这种方式永远不会奏效。该调用只是被忽略并通过。而是这样称呼它:

ConfigurationManager.RefreshSection("system.serviceModel/client");

您必须指定一个部分(客户端绑定行为...)。如果您需要更新整个配置,则循环遍历所有部分。MSDN 对这个事实保持沉默。我花了 3 天时间寻找这个废话。

于 2015-02-10T16:48:34.030 回答