zoukankan      html  css  js  c++  java
  • 对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节
    在WebConfigurationManager类中,我们首先注意到其两个属性AppSettings和ConnectionStrings。这两个属性就是用于操作我们前面看到的web.config文件中的两节appSettings和connectionStrings。下面演示使用方法。

    演示操作appSettings 节的代码:

    using System.Web.Configuration;

    ....

    string message;

    message = WebConfigurationManager.AppSettings["message"];

    ...
     


    演示操作connectionStrings节的代码:

    using System.Web.Configuration;

    ....

    string connectionString =

    WebConfigurationManager.ConnectionStrings["pubs"].ConnectionString;

    ...
     


    3.2.1.2 读取其它节
    在.NET中读取其它节要麻烦一些。我们需要利用GetSection()函数。GetSection()函数的作用是从当前web应用程序的配置文件中检索指定的配置节。GetSection()函数有2个重载,我们这里介绍GetSection(string sectionName)。这个函数参数sectionName是用于查找节点的XPath表达式(对于XPath表达式的了解请参阅其它资料)。这里我们首先需要知道的是在.NET中所有配置节都对应一个类,譬如上面我们看到的web.config文件中,appSettings节对应于AppSettingsSection类,而connectionStrings对应于ConnectionStringsSection类。利用Lutz Roeder的Reflector我们可以很容易的知道所有的section类。见下图。

    图 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);

    }
     


    上面例子中的XPath表达式system.web/identity相信大家都能猜出来是什么意思。而至于IdentitySection类到底有什么成员则需要利用Lutz Roeder的Reflector查找或MSDN查找。

    例子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();

    }
     


    在MSDN上还有其它几个例子可以参考。

    3.2.2 修改
      从图2我们可以看到还有几个静态函数OpenWebConfiguration()、OpenMachineConfiguration()等,就是用来打开一个配置文件(分别对应于web.config和machine.config)修改更新配置项的。

    例子:把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中的配置节放在单独的文件中
    我们可以把任意一个配置节(section)放入一个独立的文件中。把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.config文件:

    <appSettings>

     <add key="message" value="Hello World!"/>

    </appSettings>
     


    connections.config文件:

     <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 对某一节进行加密
    在.NET2.0中加密某一节(section),那是相当的简单。

    在配置文件中,有些信息是不希望别人看到的。例如在<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();

        WriteMessage("connections protected = " + section.SectionInformation.IsProtected);

    }
     


    此代码的作用就是加密和解密connectionStrings节。如果原来加密(通过属性IsProtected判断)了,则解密。否则相反。分别调用了UnprotectSection()和protectSection()函数。

    下面是相关文件的变化。

    加密前的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>
     

    本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/ouhaiyong/archive/2006/12/22/1453724.aspx

  • 相关阅读:
    闭包(closure)与协程共用时要注意的事情
    mysql---视图
    职责链模式
    JavaScript DOM(一)
    9.7 迭代
    [BLE--Link Layer]设备蓝牙地址
    Loopback測试软件AX1用户手冊 V3.1
    操作系统
    OpenCV特征点检測------Surf(特征点篇)
    linux 命令 xxd
  • 原文地址:https://www.cnblogs.com/fhuafeng/p/1783038.html
Copyright © 2011-2022 走看看