我需要能够以编程方式更新我的配置文件并更改我的 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/