[ASP.NET] 自定义配置节及处理

来源:互联网 发布:安卓telnet软件 编辑:程序博客网 时间:2024/06/05 15:22

1. <appsettings>

asp.net的web.config中,提供了<appsettings>来自定义一些配置。

<appsettings>是根级目录<configuration>的子级。

<appSettings><add key="uid" value="admin"/><add key="pwd" value="adminpwd"/></appSettings>

程序中,我们通过如下方式取得配置的值:

Label1.Text = WebConfigurationManager.AppSettings["uid"];

这是最简单的方式来配置和取值。如果有很多值需要配置,那么它们都将挤在<appsettings>里面,很难一眼看出哪些是配置程序的哪一块。

如果想用一个特别的名字来标识自定义的配置,让配置清晰易管理,就用下面这种方式。


2. <configSections>

<configSections>里面可以定义自己的配置节和配置节处理程序。

<configSections>是<configuration>的子级,并且紧挨着<configuration>出现。

<configSections>有两种子级:<sectionGroup>和<section>,这两种子级可以嵌套。

这两种子级常用的属性有两个:

name给自定义的配置节取个名字。

type给自定义的配置节指定一个处理程序。

在下面的例子中,仍然使用简单的值名对,使用.net内置的配置节处理程序。

<sectionGroup name="SGroup"><section name="SConfig" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0,Culture=neutral, PublicKeyToken=b77a5c561934e089" /></sectionGroup>


然后我们可以使用自定义的配置节了:

<SGroup><SConfig><add key="uid" value="admin" /><add key="pwd" value="adminpwd" /></SConfig></SGroup>


通过如下方式取值:

var sconfig = (NameValueCollection)ConfigurationManager.GetSection("SGroup/SConfig");Label1.Text = sconfig["uid"];


但要使用更复杂的配置,并且在程序中可以强类型引用,我们就必须要自定义配置节处理程序了。


3. 配置节处理程序

前面例子中的 "System.Configuration.NameValueSectionHandler"就是一个配置节处理程序,这是.net内置的值名对处理程序。

ConfigurationManager.GetSection("SGroup/SConfig")将这一段自定义的配置节读出来,传给NameValueSectionHandler对象进行处理,处理完成后返回一个object,这个object是NameValueCollection类型的,所以直接强转就行了。

下面我们来自已定义一个处理程序:

public class MySectionOneSection : ConfigurationSection    {        [ConfigurationProperty("propertyOne")]        public string PropertyOne        {            get { return (string)this["propertyOne"]; }        }        [ConfigurationProperty("MyElementOne")]        public MyElementOneSection MyElementOne        {            get { return (MyElementOneSection)this["MyElementOne"]; }        }    }

配置节处理程序要继承ConfigurationSection,然后给属性和子标签写Attribute,这是把配置节的属性名和子标签名映射为强类型的C#属性,方便代码中使用。

注意“MyElementOneSection”这个类型,这是为Section的子标签写的类,它继承自ConfigurationElement。

public class MyElementOneSection : ConfigurationElement{    [ConfigurationProperty("propertyOne")]    public string PropertyOne    {        get { return (string)this["propertyOne"]; }    }}

此时可以添加我们的配置文件节

<configSections>    <section type="ConfigHandler.MySectionOneSection, ConfigClassLib" name="MySectionOne"></section></configSections><MySectionOne propertyOne="My Section Property One"><MyElementOne propertyOne="My Element Property One"></MyElementOne></MySectionOne>

程序中这样使用它:

var mySection = (MySectionOne)ConfigurationManager.GetSection("MySectionOne");Label1.Text = mySection.MyElementOne.PropertyOne;Label2.Text = mySection.PropertyOne;

我们可以直接使用AppSetting和ConnectionString,因为系统定义好了配置节处理程序。

通过自定义配置节处理程序,我们也可以实现一样的效果,MSDN上的例子有更多Attibute的使用:

http://msdn.microsoft.com/zh-cn/library/system.configuration.configurationsection.aspx#Y3100



原创粉丝点击