ASP.NET一个网站内存放多个config文件(Web.Config文件中configSource

每个网站里都会有一个web.config文件。修改Web.config文件会导致IIS重启,就是随意的回车一下也会导致重启。微软建议,不要将需要修改的配置内容保存在web.config中。而是单独放在一个config中。

但是对于单独存放的config文件,怎么来对其进行修改和读取呢? 例如 可以指定 web.config 中的 appSetting 单独放在 一个 app-1.config 文件中。通过 configSource 来指定。

一、原来的web.config文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="CacheTimeInfo" value="30" />
    <add key="CacheTimeNews" value="10" />
    <add key="CacheTimeProduct" value="60" />
    <add key="CacheTimeTrade" value="5" />
    <add key="SiteName" value="oschina"/>
    <add key="SiteDomain" value="oschina.net"/>
  </appSettings>
  <connectionStrings/>
  <system.web>
    <compilation debug="false">
    </compilation>
    <authentication mode="Windows" />
  </system.web>
</configuration>


下面拆分成两个config文件

1)第一个config文件:web.config

1
2
3
4
5
6
7
8
9
10
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings configSource="app-1.config" />
<connectionStrings/>
  <system.web>
    <compilation debug="false">
    </compilation>
    <authentication mode="Windows" />
  </system.web>
</configuration>


2)第二个config文件:app-1.config
1
2
3
4
5
6
7
8
9
<?xml version="1.0" encoding="utf-8"?>
<appSettings>
<add key="CacheTimeInfo" value="30" />
<add key="CacheTimeNews" value="10" />
<add key="CacheTimeProduct" value="60" />
<add key="CacheTimeTrade" value="5" />
<add key="SiteName" value="oschina"/>
<add key="SiteDomain" value="oscina.net"/>
</appSettings>


那么如何读取呢?

1
2
3
4
5
Configuration config =
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
string SiteName = config.AppSettings["SiteName"];
//如果用上面这种方法会报错: CS0122: “System.Configuration.ConfigurationElement.this[System.Configuration.ConfigurationProperty]”不可访问,
因为它受保护级别限制

正确的读取方法是:

1
2
Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
string SiteName = config.AppSettings.Settings["SiteName"].Value;



修改Config值:

1
2
3
4
Configuration cfg = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
AppSettingsSection appSetting = cfg.AppSettings;
appSetting.Settings["SiteName"].Value = "changed by application"; //修改config.config中SiteName的值
cfg.Save();



总结:经过拆分后,修改config.config不会导致IIS重启。

说明:我的app-1.config文件和webconfig在同一级目录,另外,我这里叫app-1.config,你可以随意改变,比如叫app.config。

注意app-1.config的写法。
一旦在web.config中的appSettings节点中添加configSource,就不能再添加Add节点了。也就是说你不能在webconfig里放一部分<add>,然后再config.config里在放一部分<add> 修改时,访问的节点必须存在否则会报:未将对象引用设置到对象的实例。
posted @   游子善心  阅读(9)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
点击右上角即可分享
微信分享提示