`
380071587
  • 浏览: 447269 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

使用 ConfigurationSection 创建自定义配置节

 
阅读更多
我们可以通过用自己的 XML 配置元素来扩展标准的 ASP.NET 配置设置集,要完成这一功能,我们必须实现继承System.Configuration.ConfigurationSection 类来实现自定义配置节,在1.0中当然也可以通过IconfigurationSectionHandler 接口创建自定义配置节!这里我们主要学一下通过ConfigurationSection类来实现简单的配置处理程序.
先看一下在web.config文件中的配置情况,在这里有两个元素,第一个mysection,有两个属性user,password,第二个也有两个属性element1,和element2。配置比较简单。
<!--//////////////////////////////////////////////////////////////////////////////////////////////-->
<configSections>
<sectionGroupname="mygroup">
<sectionname="mysection"
type
="ConfigSection"
allowDefinition
="Everywhere"
allowLocation
="true"/>
</sectionGroup>
</configSections>
<!--//////////////////////////////////////////////////////////////////////////////////////////////-->

<mygroup>
<mysectionuser="用户"password="密码">
<elementelement1="属性1"element2="属性2"></element>
</mysection>
</mygroup>

理解配置文件结构后,我们就需要用继承自System.Configuration.ConfigurationSection的基类来实现简单的配置类ConfigSection,在2.0中,我们只需要这一个类就能实现完成配置,下面请看代码:
usingSystem;
usingSystem.Data;
usingSystem.Configuration;
usingSystem.Web;
usingSystem.Web.Security;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
usingSystem.Web.UI.WebControls.WebParts;
usingSystem.Web.UI.HtmlControls;

///<summary>
///ConfigSection的摘要说明
///</summary>
publicclassConfigSection:ConfigurationSection
{
publicConfigSection()
{
//
//TODO:在此处添加构造函数逻辑
//
}
[ConfigurationProperty(
"user",DefaultValue="yanghong",IsRequired=true)]
publicstringUser
{
get{return(string)this["user"];}
set{this["user"]=value;}
}

[ConfigurationProperty(
"password",DefaultValue="password",IsRequired=true)]
publicstringPassWord
{
get{return(string)this["password"];}
set{this["password"]=value;}
}

[ConfigurationProperty(
"element")]
publicelementinfoElement
{
get{return(elementinfo)this["element"];}
set{this["element"]=value;}
}
}
publicclasselementinfo:ConfigurationElement
{
publicelementinfo(){}


[ConfigurationProperty(
"element1",DefaultValue="element1",IsRequired=true)]
publicstringElement1
{
get{return(string)this["element1"];}
}

[ConfigurationProperty(
"element2",DefaultValue="element2",IsRequired=true)]
publicstringElement2
{
get{return(string)this["element2"];}
}


}



通过下面的代码就可以获得在配置文件中设置的值了
ConfigSectionconfig=(ConfigSection)ConfigurationManager.GetSection("mygroup/mysection");
Response.Write(
"用户名:"+config.User.ToString()+"密码:"+config.PassWord.ToString()+"元素属性:"+config.Element.Element1.ToString()+config.Element.Element2.ToString());
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics