您可以覆盖 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"];
干杯马丁