【整理】Asp.Net2.0配置管理

    众所周知,Asp.Net程序的配置文件可以对整台机器整个IIS服务器单个Asp.Net应用程序、Asp.Net应用程序的子目录以及单个文件施加影响。在C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG目录下有四个文件:machine.config、machine.config.comments、web.config和web.config.comments,其中的machine.config对整台机器施加影响,web.config对整个IIS服务器施加影响;而两个后缀名为.comments的文件是分别对这两个文件的详细描述,可以用记事本或IDE代开,这个有别于Asp.Net1.x版本,目的就是为了让machine.config和web.config这两个文件变得更加轻便,同时这两个文件里面除了注释而外就是machine.config和web.config文件相同的默认配置,如果由于我们更改这两个配置文件而导致错误的话,此文件就可以充当备份,我们可以在其中拷贝一份默认的代码来覆盖我们更改过的,就会回到默认配置,貌似很强大,呵呵~~。

    配置文件的继承状态:子目录下网页文件的配置文件:子目录配置文件:网站配置文件:整个IIS服务器配置文件:整台机器配置文件。这里面的意思我就不多说了,用.Net的继承去理解一下就可以了。

    配置节处理程序声明:配置节处理程序的声明在配置文件的configSections节点中,同时这个节点必须是Configuration的第一个元素。如下所示:

<configuration>
    
<configSections>
        
<section name="appSettings" type="System.Configuration.AppSettingsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" restartOnExternalChanges="false" requirePermission="false"/>
        
<section name="connectionStrings" type="System.Configuration.ConnectionStringsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" requirePermission="false"/>
        
<section name="mscorlib" type="System.Configuration.IgnoreSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" allowLocation="false"/>
        
<section name="runtime" type="System.Configuration.IgnoreSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" allowLocation="false"/>
                
</configSections>
<configuration>
其中的name值就是节点名称,type后面的值以"appSettings"为例System.Configuration.AppSettingsSection, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a,红色代表处理程序所在的类,蓝色代表该类所在的程序集名称。
    配置节设置:位于配置节处理程序声明之后,它包含实际的配置设置,也可以有自己的子元素,这些子元素同其父元素一样,用父元素的处理程序来处理。示例如下:
    配置节处理程序声明:
<section name="pages" type="System.Web.Configuration.PagesSection, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
    配置节设置
 <pages>
            
<namespaces>
                
<add namespace="System"/>
                
<add namespace="System.Collections"/>
                
<add namespace="System.Collections.Specialized"/>
                
<add namespace="System.Configuration"/>
                
<add namespace="System.Text"/>
                
<add namespace="System.Text.RegularExpressions"/>
                
<add namespace="System.Web"/>
                
<add namespace="System.Web.Caching"/>
                
<add namespace="System.Web.SessionState"/>
                
<add namespace="System.Web.Security"/>
                
<add namespace="System.Web.Profile"/>
                
<add namespace="System.Web.UI"/>
                
<add namespace="System.Web.UI.WebControls"/>
                
<add namespace="System.Web.UI.WebControls.WebParts"/>
                
<add namespace="System.Web.UI.HtmlControls"/>
            
</namespaces>

            
<controls>
                
<add tagPrefix="asp" namespace="System.Web.UI.WebControls.WebParts" assembly="System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
            
</controls>
        
</pages>
    Asp.Net2.0 MMC管理单元:此工具是2.0以后推出的可视化配置管理单元,可以配置IIS服务器、网站、Asp.Net应用程序的配置文件,要求必须要有本机的管理权限。如下图,分别有"编辑全局配置"和"编辑配置",可以通过可视化界面配置如常规、自定义错误、授权、身份验证、应用程序、状态管理和位置等节点。
     

    网站管理工具:此功能允许我们使用浏览器管理网站配置文件,在本地和远程都可操作,不需要本机的管理员权限即可操作,但是要有网站的管理权限。打开方式一:解决方案资源管理器>>,打开方式二:"项目"菜单>>Asp.Net配置。此方式配置的内容要比MMC下面少,原因是考虑到了安全因素,但大多数常见的节点都可以通过它来设置。这个主要是用来弥补MMC下需要本机管理员的一种补充方案。

    Asp.Net2.0配置API:所有配置相关的类是存在于System.Configuration命名空间中的;所有的配置包括machine.config和web.config都是用System.Configuration.Configuration类下面的方法来操作的;所有的web.config相关的类是存在于System.Web.Configuration命名空间的;所有的web.config都是用System.Web.Configuration.WebConfigurationManager类下的方法来处理的。以下为各种情形下的程序示例:

    1.在上级web.config中指定某个子目录或单个文件的配置文件

    Asp.Net应用程序web.config如下,有两层意思:第一个Location节点表示禁止所有用户访问SubFolder目录下的文件,第二个Location节点表示允许所有用户访问SubFolder目录下的validatorUserIsNoLogin.aspx文件。两个合起来的意思就是允许用户只能访问SubFolder目录下的validatorUserIsNoLogin.aspx文件。

<?xml version="1.0"?>
<configuration>
    
<appSettings/>
    
<connectionStrings/>
    
<system.web>
        
<!-- 
            设置 compilation debug
="true" 可将调试符号插入
            已编译的页面中。但由于这会 
            影响性能,因此只在开发过程中将此值 
            设置为 
true
        
-->
        
<compilation debug="true">
        
</compilation>
        
<!--
            通过 
<authentication> 节可以配置 ASP.NET 用来 
            识别进入用户的
            安全身份验证模式。 
        
-->
  
<!--
            如果在执行请求的过程中出现未处理的错误,
            则通过 
<customErrors> 节可以配置相应的处理步骤。具体说来,
            开发人员通过该节可以配置
            要显示的 html 错误页
            以代替错误堆栈跟踪。

        
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
            
<error statusCode="403" redirect="NoAccess.htm" />
            
<error statusCode="404" redirect="FileNotFound.htm" />
        
</customErrors>
        
-->
    
</system.web>
  
<location path="SubFolder" allowOverride="true">
    
<system.web>
      
<authorization>
        
<deny users="*"/>
      
</authorization>
    
</system.web>
  
</location>
  
<location path="SubFolder/validatorUserIsNoLogin.aspx">
    
<system.web>
      
<authorization>
        
<allow users="*"/>
      
</authorization>
    
</system.web>
  
</location>
</configuration>

    上图中的allowOverride="true"表示允许子目录重写此此节点,否则不能重写。在SubFolder目录中的web.config中重写如下:

<?xml version="1.0" encoding="utf-8"?>
<!-- 
    注意: 除了手动编辑此文件以外,您还可以使用 
    Web 管理工具来配置应用程序的设置。可以使用 Visual Studio 中的
     “网站”
->“Asp.Net 配置”选项。
    设置和注释的完整列表在 
    machine.config.comments 中,该文件通常位于 
    \Windows\Microsoft.Net\Framework\v2.x\Config 中
-->
<configuration>
    
<appSettings/>
    
<connectionStrings/>
    
<system.web>
      
<authorization>
        
<allow users="*"/>
      
</authorization>
    
</system.web>
</configuration>

    由于上级配置文件中的节点被子目录配置文件重写,重写后的效果是允许所有用户访问SubFolder目录下的页面。

    注意:如果将上级目录中第二个Location节点改为如下:

  <location path="SubFolder/validatorUserIsNoLogin.aspx">
    
<system.web>
      
<authorization>
        
<deny users="*"/>
      
</authorization>
    
</system.web>
  
</location>

    那么意思就是允许所有用户访问SubFolder目录中除validatorUserIsNoLogin.aspx而外的所有文件。即就是页面配置文件拥有最高优先权。

    2.在子目录web.config中重写上级web.config相应节点

    Asp.Net应用程序web.config如下,意思是当前网站应用程序禁止一切用户访问

<?xml version="1.0"?>
<configuration>
    
<appSettings/>
    
<connectionStrings/>
    
<system.web>
                   
<authorization>
                       
<deny users="*"/>
                   
</authorization>
    
</system.web>
</configuration>

     在目录SubFolder下的web.config如下,配置后当前应用程序只有SubFolder下的页面可允许访问。

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    
<appSettings/>
    
<connectionStrings/>
    
<system.web>
      
<authorization>
        
<allow users="*"/>
      
</authorization>
    
</system.web>
</configuration>

 

    3.读取当前应用程序的继承配置

protected void Button1_Click(object sender, EventArgs e)
        {
            System.Configuration.Configuration config 
= System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/Demo0");
            config.SaveAs(
@"F:\Website\MyApp.web.config", System.Configuration.ConfigurationSaveMode.Full, true);

        }

 

    4.读取任一节点的值

    读取配置文件中System.Web节点下compilation子节点Debug属性值。

        protected void Button1_Click(object sender, EventArgs e)
        {
            
string path = "/Demo0";

            
//打开指定虚拟路径下的web.config文件以允许读写操作
            Configuration config = WebConfigurationManager.OpenWebConfiguration(path);

            
//获取要操作的配置节,在这里我们获取的是system.web下的compilation节点
            CompilationSection section = config.GetSection("system.web/compilation"as CompilationSection;

            System.Text.StringBuilder strBuilder 
= new System.Text.StringBuilder();
            strBuilder.Append(
"debug:");

            
//section.Debug.ToString()用于获取或设置Debug属性值
            strBuilder.Append(section.Debug.ToString());

            
this.Label1.Text = strBuilder.ToString();
        }

 

    5.Asp.Net1.x下使用IConfigurationSectionHanddler创建自定义配置节处理程序

    首先,在web.config中声明配置节处理程序

<configuration>
  
<configSections >
    
<section name="customConnStr" type="MyConfigSectionHanddler.CustomConnStr,MyConfigSectionHanddler,Version=2.0.0.0, Culture=neutral, PublicKeyToken=null" allowDefinition="Everywhere" allowLocation="true"/>
  
</configSections>
  
<customConnStr>
    
<add key="Ext_SvrName" value="jewleo\SQL2005"/>
    
<add key="Ext_DBName" value="aspnetdb"/>
    
<add key="Ext_UID" value="sa"/>
    
<add key="Ext_Pwd" value="sa"/>
  
</customConnStr>
    
<appSettings/>
    
<connectionStrings/>
    
<system.web>
        
<!-- 
            设置 compilation debug
="true" 可将调试符号插入
            已编译的页面中。但由于这会 
            影响性能,因此只在开发过程中将此值 
            设置为 
true
        
-->
        
<compilation debug="true">
        
</compilation>
        
<!--
            通过 
<authentication> 节可以配置 ASP.NET 用来 
            识别进入用户的
            安全身份验证模式。 
        
-->
  
<!--
            如果在执行请求的过程中出现未处理的错误,
            则通过 
<customErrors> 节可以配置相应的处理步骤。具体说来,
            开发人员通过该节可以配置
            要显示的 html 错误页
            以代替错误堆栈跟踪。

        
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
            
<error statusCode="403" redirect="NoAccess.htm" />
            
<error statusCode="404" redirect="FileNotFound.htm" />
        
</customErrors>
        
-->
    
</system.web>
</configuration>

    定义配置节处理程序,在Asp.Net1.x中必须继承自IConfigurationSectionHanddler接口

using System;
using System.Collections;
using System.Text;
using System.Collections.Specialized;
using System.Configuration;
using System.Xml;

namespace MyConfigSectionHanddler
{
    
public class CustomConnStr : IConfigurationSectionHandler
    {
        
private const String EXT_SVRNAME = "Ext_SvrName";
        
private const String EXT_DBNAME = "Ext_DBName";
        
private const String EXT_UID = "Ext_UID";
        
private const String EXT_PWD = "Ext_Pwd";

        
private static String mstrExt_SvrName;
        
private static String mstrExt_DBName;
        
private static String mstrEXT_UID;
        
private static String mstrEXT_PWD;
        
private static string mstrAppRoot;

        
public object Create(object parent, object configContext, XmlNode section)
        {
            NameValueCollection settings;

            
try
            {
                NameValueSectionHandler baseHanddler 
= new NameValueSectionHandler();
                settings 
= baseHanddler.Create(parent, configContext, section) as NameValueCollection;
            }
            
catch
            {
                settings 
= null;
            }

            
if (settings == null)
            { 

            }
            
else
            {
                mstrExt_SvrName 
= ReadSetting(settings, EXT_SVRNAME, string.Empty);
                mstrExt_DBName 
= ReadSetting(settings, EXT_DBNAME, string.Empty);
                mstrEXT_UID 
= ReadSetting(settings, EXT_UID, string.Empty);
                mstrEXT_PWD 
= ReadSetting(settings, EXT_PWD, string.Empty);
            }

            
return null;
        }

        
/// <summary>
        
/// 检索当前应用程序的名为customConnStr的配置节
        
/// </summary>
        
/// <param name="strAppPath">应用程序路径</param>
        public static void OnApplicationStart(String strAppPath)
        {
            mstrAppRoot 
= strAppPath;
            System.Configuration.ConfigurationManager.GetSection(
"customConnStr");
        }

        
/// <summary>
        
/// 根据NameValueCollection对象中的key获取value
        
/// </summary>
        
/// <param name="settings">NameValueCollection对象</param>
        
/// <param name="key">NameValueCollection对象中的key</param>
        
/// <param name="defaultValue">默认值</param>
        
/// <returns>String类型 获取到的值</returns>
        public static String ReadSetting(NameValueCollection settings, String key, string defaultValue)
        {
            
try
            {
                
object setting = settings[key];
                
return (setting == null? defaultValue : (String)setting;
            }
            
catch
            {
                
return defaultValue;
            }
        }

        
public static string ConnectionStringExt
        {
            
get 
            {
                
string connectStr;
                connectStr 
= "servername=" + mstrExt_SvrName + ";database=" + mstrExt_DBName + ";uid=" + mstrEXT_UID + ";pwd=" + mstrEXT_PWD;
                
return connectStr;
            }
        }
    }
}

    下面是测试程序
    首先在Global.asax中添加如下代码

        protected void Application_Start(object sender, EventArgs e)
        {
            MyConfigSectionHanddler.CustomConnStr.OnApplicationStart(
"/Demo0");
        }

    然后如下用主程序调用

        protected void Button1_Click(object sender, EventArgs e)
        {
            Label1.Text 
= MyConfigSectionHanddler.CustomConnStr.ConnectionStringExt;
        }


    6.Asp.Net2.0使用ConfigurationSection创建自定义配置节处理程序,这个新增的特性创建配置节处理程序很方便,不像上面那样,有太多的逻辑来写,废话不说了,代码来了。

    首先,在web.config中声明配置节处理程序

<?xml version="1.0"?>
<configuration>
  
<configSections >
    
<section name="customSectionAttribute" type="MyConfigSectionHanddler.CustomSectionAttribute,MyConfigSectionHanddler,Version=2.0.0.0,Culture=neutral,PublicKeyToken=null" allowDefinition="Everywhere" allowLocation="true"/>
  
</configSections>
  
<customSectionAttribute myAttrib1="Clowns">
    
<myChildSection myChildAttrib1="Zippytest" myChildAttrib2="Michael Zawondy test "/>
  
</customSectionAttribute>
    
<appSettings/>
    
<connectionStrings/>
    
<system.web>
        
<!-- 
            设置 compilation debug
="true" 可将调试符号插入
            已编译的页面中。但由于这会 
            影响性能,因此只在开发过程中将此值 
            设置为 
true
        
-->
        
<compilation debug="true">
        
</compilation>
        
<!--
            通过 
<authentication> 节可以配置 ASP.NET 用来 
            识别进入用户的
            安全身份验证模式。 
        
-->
  
<!--
            如果在执行请求的过程中出现未处理的错误,
            则通过 
<customErrors> 节可以配置相应的处理步骤。具体说来,
            开发人员通过该节可以配置
            要显示的 html 错误页
            以代替错误堆栈跟踪。

        
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
            
<error statusCode="403" redirect="NoAccess.htm" />
            
<error statusCode="404" redirect="FileNotFound.htm" />
        
</customErrors>
        
-->
    
</system.web>
</configuration>

     其次,定义配置节处理程序,其实当中最重要的就是Attribute的使用

using System;
using System.Configuration;

namespace MyConfigSectionHanddler
{
    
public class CustomSectionAttribute : ConfigurationSection
    {
        
public CustomSectionAttribute()
        {
 
        }

        
public CustomSectionAttribute(String attribVal)
        {
            MyAttrib1 
= attribVal;
        }

        [ConfigurationProperty(
"myAttrib1", DefaultValue = "Clowns", IsRequired = true)]
        [StringValidator(InvalidCharacters
="=!@#$%^&*?/\\",MaxLength=60,MinLength=1)]
        
public String MyAttrib1
        {
            
get {
                
return (String)this["myAttrib1"];
            }
            
set {
                
this["myAttrib1"= value;
            }
        }
        [ConfigurationProperty(
"myChildSection")]
        
public MyChildConfigElement MyChildSection
        {
            
get {
                
return (MyChildConfigElement)this["myChildSection"];
            }
            
set 
            {
                
this["myChildSection"= value;
            }
        }


        
public class MyChildConfigElement : ConfigurationElement
        {
            
public MyChildConfigElement()
            { 
            }

            
public MyChildConfigElement(String a1,String a2)
            {
                MyChildAttrib1 
= a1;
                MyChildAttrib2 
= a2;
            }

            [ConfigurationProperty(
"myChildAttrib1", DefaultValue = "Zippytest", IsRequired = true)]
            [StringValidator(InvalidCharacters 
= "=!@#$%^&*?/\\", MaxLength = 60, MinLength = 1)]
            
public String MyChildAttrib1
            {
                
get 
                {
                    
return (String)this["myChildAttrib1"];
                }
                
set 
                {
                    
this["myChildAttrib1"= value;
                }
            }

            [ConfigurationProperty(
"myChildAttrib2", DefaultValue = "Michael Zawondy test ", IsRequired = true)]
            [StringValidator(InvalidCharacters 
= "=!@#$%^&*?/\\", MaxLength = 60, MinLength = 1)]
            
public String MyChildAttrib2
            {
                
get 
                {
                    
return (String)this["myChildAttrib2"];
                }
                
set 
                {
                    
this["myChildAttrib2"= value;
                }
            }
        }
    }
}
    主程序调用
        protected void Button1_Click(object sender, EventArgs e)
        {
            MyConfigSectionHanddler.CustomSectionAttribute config 
=
    (MyConfigSectionHanddler.CustomSectionAttribute)System.Configuration.ConfigurationManager.GetSection(
    
"customSectionAttribute");

            StringBuilder sb 
= new StringBuilder();

            sb.Append(
"<h2>Attributes in the myCustomSection Element:</h2>");
            sb.AppendFormat(
"myAttrib1 = {0}<br/>", config.MyAttrib1.ToString());
            sb.Append(
"<h2>Attributes in the myChildSection Element:</h2>");
            sb.AppendFormat(
"myChildAttrib1 = {0}<br/>", config.MyChildSection.MyChildAttrib1.ToString());
            sb.AppendFormat(
"myChildAttrib2 = {0}<br/>", config.MyChildSection.MyChildAttrib2.ToString());

            Label1.Text 
= sb.ToString();
            Label1.Visible 
= true;
        }
posted @ 2009-06-18 16:44  网络渔夫  阅读(628)  评论(0编辑  收藏  举报