对Web.config配置文件的常见操作对于配置文件的常见操作包括: l 读取 l 修改 l 将web.config中的配置节放在单独的文件中 l 对某一节进行加密 l 添加定制的节 操作web配置文件(包括machine.config和web.config等)的命名空间是:System.Web.Configuration。主要应用的类是:WebConfigurationManager。下面看看WebConfigurationManager类的成员。(可以利用MSDN来查看,我下面是利用Lutz Roeder的Reflector)
图 1 WebConfigurationManager类成员 3.2.1 读取 图 2 WebConfigurationManager类中用于读取的属性和方法 3.2.1.1 读取appSettings节和connectionStrings节 演示操作appSettings 节的代码: using System.Web.Configuration; .... string message; message = WebConfigurationManager.AppSettings["message"]; ...
using System.Web.Configuration; .... string connectionString = WebConfigurationManager.ConnectionStrings["pubs"].ConnectionString; ...
图 3 继承于ConfigurationSection类的各section类 从中我们查找到compilation节对应于System.Web.Configuration. CompilationSection 类,authentication节对应于System.Web.Configuration.AuthenticationSection类,identity节对应于System.Web.Configuration.IdentitySection类,等等。 例子1: protected void readImpersonationButton_Click(object sender, EventArgs e) { IdentitySection section; section = WebConfigurationManager.GetSection("system.web/identity") as IdentitySection; if (section != null) { WriteMessage("Impersonate = " + section.Impersonate); } } private void WriteMessage(string message) { //在页面上添加一个名为messagePlaceHolder的PlaceHolder控件 HtmlGenericControl generic = new HtmlGenericControl(); generic.InnerHtml = message; messagePlaceHolder.Controls.Add(generic); }
例子2:(MSDN上的例子)此示例演示一个可从 Web 应用程序或控制台应用程序访问的节。 // Show the use of GetSection(string). // It gets the connectiobStrings section. // If called from within a client application, // the GetSection(string) gets the default connectionStrings // section from the machine.config. // If called from within a Web aplication it gets the // section from the configuration file located at the // application current level. static void GetSection1() { // Get the connectionStrings section. ConnectionStringsSection connectionStringsSection = WebConfigurationManager.GetSection("connectionStrings") as ConnectionStringsSection; // Get the connectionStrings key,value pairs collection. ConnectionStringSettingsCollection connectionStrings = connectionStringsSection.ConnectionStrings;
// Get the collection enumerator. IEnumerator connectionStringsEnum = connectionStrings.GetEnumerator(); // Loop through the collection and // display the connectionStrings key, value pairs. int i = 0; Console.WriteLine("[Display the connectionStrings]"); while (connectionStringsEnum.MoveNext()) { string name = connectionStrings[i].Name; Console.WriteLine("Name: {0} Value: {1}", name, connectionStrings[name]); i += 1; } Console.WriteLine(); }
3.2.2 修改 例子:把system.web项下的compilation修改(false->true;或true->false)。 protected void toggleDebugButton_Click(object sender, EventArgs e) { Configuration config; config = WebConfigurationManager.OpenWebConfiguration("~"); CompilationSection compilation; compilation = config.GetSection("system.web/compilation") as CompilationSection; if (compilation != null) { compilation.Debug = !compilation.Debug; config.Save(); WriteMessage("Debug setting is now: " + compilation.Debug); } } 修改的注意点: 1. 必须对该文件有修改的权限,通常NETWORK SERVICE和ASPNET账户对文件和目录没有修改权限。 2. ASP.NET在运行时,Runtime时刻注视着web.config文件的变化,一旦该文件修改了,整个应用程序就创建一个新的实例,并重新加载。如果频繁的修改web.config文件,对程序性能影响比较大。 3. 如果需要频繁修改配置,则应把该配置节放到单独的文件中。 3.2.3 将web.config中的配置节放在单独的文件中 例子: web.config文件 <?xml version="1.0"?> <configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"> <appSettings configSource="appSettings.config"/> <connectionStrings configSource="connections.config"/> <system.web> <compilation debug="true" /> <authentication mode="Windows"/> <identity impersonate="true"/> </system.web> </configuration>
<appSettings> <add key="message" value="Hello World!"/> </appSettings>
<connectionStrings> <add name="AdventureWorks" connectionString="..."/> <add name="pubs" connectionString="..."/> </connectionStrings>
1. 可以根据不同的环境而设置不同的配置,譬如开发环境、测试环境、正式环境配置不同的数据库连接。 2. 权限管理。例如,可以锁住web.config不让某些人修改,而只让其用于修改appSettings.config文件的权限。 3. 利用外部配置文件,还可以控制当其修改后应用程序是否重启。一般,当我们修改了web.config文件时,应用程序就产生一个新的实例并重启。而如果是单独的配置文件,则可以控制重启与否。 配置方法:在machine.config中配置。Machine.config文件一般在C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG目录下。打开machine.config文件,截图如下:
图 4 machine.config文件内容截图 从图4我们可以看到在有的元素中有restartOnExternalChanges属性。如果设为false,则外部文件修改后不重启,如果设为true,则重启。 3.2.4 对某一节进行加密 在配置文件中,有些信息是不希望别人看到的。例如在<connectionStrings>节中可能包含连接数据库的用户名和密码。<identity>节中也可能包含用户名和密码。 注意:有些节可能含有密码,但不能加密,例如<processModel>节,为了安全,你可以应用Aspnet_setreg.exe工具来保存密码。
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(); WriteMessage("connections protected = " + section.SectionInformation.IsProtected); }
下面是相关文件的变化。 加密前的connectionStrings.config文件内容如下:
图 5 加密前的connectionStrings.config文件内容 加密后connectionStrings.config文件内容如下:
图 6 加密后connectionStrings.config文件内容 对于结果的改变,我们可以对比一下,自己了解其变化。 但在上面的代码片断中,我们还有一个地方需要了解:加密提供者。目前有两种加密提供者:DataProtectionConfigurationProvider 和 RSAProtectedConfigurationProvider。其中DataProtectionConfigurationProvider是利用Windows Data Protection API(DPAPI)提供与机器相关的加密解密。也就是说我们在哪一台机器上加密就只能在那一台机器上解密。如果需要在其它机器上解密则只能使用DataProtectionConfigurationProvider。 3.2.5添加定制的配置节 <configuration> <configSections> <section name="Logging" type="System.Configuration.NameValueSectionHandler" /> </configSections> <Logging> <add key="File Name" value="MyApp.log" /> <add key="MessageColumns" value="5" /> <add key="MaxFileSize" value="40000000000000" /> </Logging> </configuration> |
|