不同web应用程序的通用web.config连接字符串
本文关键字:web config 连接 字符串 应用程序 不同 | 更新日期: 2023-09-27 18:24:00
我们有多个web应用程序,并将所有web应用程序部署在名为iapps的同一文件夹中。但每个应用程序都有自己的web.config文件,并且大多数应用程序都必须具有commmon连接字符串。
现在我想制作一个通用的配置文件,让所有的应用程序读取连接字符串并使用它。我们如何做到这一点?任何好的文章或例子
电流
'iapps'app1
|- web.config
'iapps'app2
|- web.config
'iapps'app3
|- web.config
预期
'iapps'app1 --Web.cofig
|-root Config <-|
'iapps'app2 --Web.cofig
|-root Config <-|
'iapps'app3 --Web.cofig
|-root Config <-|
这个答案已经描述了几种替代方案。此外,您还可以利用继承的思想,将web.config
中的所有公共连接字符串放在根目录下(即本例中的iApps)。
app1…appN将全部继承iapps'web.config
的设置
请注意,您在iapps'web.config
中定义的任何节都不会在子应用程序的web.config中重新定义,否则您的子应用程序中将出现重复的节定义错误。
您可以覆盖AppDomain对象中的配置。
您的web.config可能如下所示:
<?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>
在你的PageLoad事件中,你可以使用这个:
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);
}
现在您可以从配置设置中读取您的设置:
var key1Value = webApp1Config["Key1"];
干杯Martin