在FrameWork框架下主要有2个配置文件,一个是machine.config一个是web.config。当然web.config是项目中最常用的,并且配置文件中的信息内容也很多,尤其在项目加大和导入其他框架时,配置内容就显得有些多、乱、杂。那是不是可以重新整理分割我们的配置文件呢。答案是可以的。那就是添加外部配置文件,把可以独立出来的信息单独放到一个新的配置文件中。例如appsetting或connectionstring.
一. 把appsetting配置信息外移
在原web.config文件中,把<appSettings><add xxxxxx />...........</appSetting>的内容改写为:
<appSettings configSource="appSettings.config"/>或<appSettings file="appSettings.config">
在appsettings.config文件中写入:
<?xml version="1.0"?><appSettings><add xxxxx />........</appSetting>
二. 把connectionStrings配置外移
在原web.config文件中,把<connectionStrings>........</connectionStrings>的内容改为:
<connectionStrings configSource="connectionString.config">
在connectionString.config文件中写入:
<?xml version="1.0"?><connectionStrings><add xxxxx />......</connectionStrings>
三. 配置自定义配置与自定义结点结点外移
1. 继承相关的类
2. 对config的操作调用
四. 对配置文件的读写操作
配置文件主要的读写操作类是WebConfigurationManager
1. appSetting读取 WebConfigurationManager.AppSettings["xxxx"];
2. connectionString读取 WebConfigurationManager.ConnectionStrings["pubs"].ConnectionString;
3. 通用结点的读取 WebConfigurationManager.GetSection(XPath);
4. 结点的修改
五. 某一结点进行加密
在配置文件中,有些信息是不希望别人看到的。例如在<connectionStrings>节中可能包含连接数据库的用户名和密码。<identity>节中也可能包含用户名和密码。
注意:有些节可能含有密码,但不能加密,例如<processModel>节,为了安全,你可以应用Aspnet_setreg.exe工具来保存密码。 |
下面的例子演示如何加密和解密一节。提醒,这里的加密和解密用的单词是protect和unprotect。注意:在实际应用中,我们并不需要明确的调用解密函数。在运行市,程序读取到加密了的配置节时将会自动调用解密。
protected void toggleEncryptionButton_Click(object sender, EventArgs e) { Configuration config; config = WebConfigurationManager.OpenWebConfiguration("~"); ConnectionStringsSection section; section = config.GetSection("connectionStrings") as ConnectionStringsSection; if (section.SectionInformation.IsProtected) { section.SectionInformation.UnprotectSection(); } else { section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider"); } config.Save(); } |
此代码的作用就是加密和解密connectionStrings节。如果原来加密(通过属性IsProtected判断)了,则解密。否则相反。分别调用了UnprotectSection()和protectSection()函数。
public void UpdateSectionElementInfo()
{
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
CompilationSection section = config.GetSection("system.web/compilation") as CompilationSection;
if (compilation != null)
{
compilation.Debug = !compilation.Debug;
config.Save();
}
}
但在上面的代码片断中,我们还有一个地方需要了解:加密提供者。目前有两种加密提供者:DataProtectionConfigurationProvider 和 RSAProtectedConfigurationProvider。其中DataProtectionConfigurationProvider是利用Windows Data Protection API(DPAPI)提供与机器相关的加密解密。也就是说我们在哪一台机器上加密就只能在那一台机器上解密。如果需要在其它机器上解密则只能使用DataProtectionConfigurationProvider。
注意点:
1. 必须对该文件有修改的权限,通常NETWORK SERVICE和ASPNET账户对文件和目录没有修改权限。
2. ASP.NET在运行时,web.config文件的变化,整个应用程序就创建一个新的实例,并重新加载。 如果需要频繁修改配置,
则应把该配置节放到单独的文件中。