Trouble writing programmatic config changes for WCF
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 (ServiceEndpointElem开发者_Python百科ent 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
I changed two things, and it works just fine for me:
1) I am using OpenExeConfiguration
with the assembly path
2) I'm accessing the <services>
section, rather than the <system.serviceModel>
section group
With those two changes, everything works just fine:
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);
Just in case...if you have some weird magic with not updating app.config after calling RefreshSection method, make sure that you do not call it like in the original post:
ConfigurationManager.RefreshSection("system.serviceModel");
This way it never works. The call is just ignored and passed by. Instead call it like this:
ConfigurationManager.RefreshSection("system.serviceModel/client");
You must specify a section (client, bindings, behaviors, ...). If you need to update the whole config, then iterate through all the sections in a cycle. MSDN stays silent about this fact. I have spent 3 days searching for this crap.
精彩评论