We have multiple web applications and deploy all web applications in same folder called iapps. But each app has its own web.config file and must most of the have commmon connection strings.
Now I want to make a common configuration file which all the application read the connection strings and use it. How can we do that? Any good articles or examples
\iapps\app1
|- web.config
\iapps\app2
|- web.config
\iapps\app3
|- web.config
Expecting
\iapps\app1 --Web.cofig
|-root Config <-|
\iapps\app2 --Web.cofig
|-root Config <-|
\iapps\app3 --Web.cofig
|-root Config <-|
This answer already describes several alternatives. In addition, you can also leverage the idea of inheritance by placing all common connection strings in web.config
under root (ie iApps in this case).
app1...appN will all inherit settings from iapps\\web.config
Just be careful that anythinn you define in iapps\\web.config
doesn't get redefined in child apps' web.config, else you'll get duplicate section defined error in your child apps.
You can override the configuration in your AppDomain object.
Your web.config could look like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="WebApp1" type="System.Configuration.NameValueSectionHandler, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<section name="WebApp2" type="System.Configuration.NameValueSectionHandler, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
</configSections>
<WebApp1>
<add key="Key1" value="App1 value"/>
</WebApp1>
<WebApp2>
<add key="Key1" value="App2 value"/>
</WebApp2>
</configuration>
And in your PageLoad event you could use this:
SetConfig();
var webApp1Config = ConfigurationManager.GetSection("WebApp1") as NameValueCollection;
var webApp2Config = ConfigurationManager.GetSection("WebApp2") as NameValueCollection;
private static void SetConfig()
{
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", @"C:\Temp\web.config");
var fieldInfo = typeof(ConfigurationManager).GetField("s_initState", BindingFlags.NonPublic | BindingFlags.Static);
if (fieldInfo != null)
fieldInfo.SetValue(null, 0);
var field = typeof(ConfigurationManager).GetField("s_configSystem", BindingFlags.NonPublic | BindingFlags.Static);
if (field != null)
field.SetValue(null, null);
var info = typeof(ConfigurationManager).Assembly.GetTypes().First(x => x.FullName == "System.Configuration.ClientConfigPaths").GetField("s_current", BindingFlags.NonPublic | BindingFlags.Static);
if (info != null)
info.SetValue(null, null);
}
Now you can read your settings from the configuration settings:
var key1Value = webApp1Config["Key1"];
Cheers Martin
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.