ASP.NET杂谈-一切都从web.config说起(2)(ConfigSections详解-中)
我们就接着html" target=_blank>上一篇继续说,上一篇中介绍了ConfigSection的结构和两个简单的DEMO,本篇就说一下SectionGroup、ConfigurationElementCollection和key/value pair configurationsection.
的使用。
1、SectionGroup的使用
--------------------------------------------------------------------------------
下面的代码简单的说明一下SectionGroup的使用:
1)、首先定义一个继承ConfigurationSectionGroup的类:
1: /// <summary>
2: /// 自定义SectionGroup
3: /// </summary>
4: public class MySectionGroup:ConfigurationSectionGroup
5: {
6: [ConfigurationProperty("myBlog")]
7: public MySection MyBlog
8: {
9: get
10: {
11: return (MySection)base.Sections["myBlog"];
12: }
13: }
14: }
2)、其次,在定义一个继承ConfigurationSection的Section:
1: /// <summary>
2: /// 自定义Section
3: /// </summary>
4: public class MySection:ConfigurationSection
5: {
6: [ConfigurationProperty("name")]
7: public string BlogName
8: {
9: get
10: {
11: return (string)base["name"];
12: }
13: }
14: [ConfigurationProperty("url")]
15: public string BlogUrl
16: {
17: get
18: {
19: return (string)base["url"];
20: }
21: }
22: }
下面再讨论一下怎么在web.config中如何配置和使用:
web.config中的配置:
1: <configSections>
2: <sectionGroup name="myBlogs" type="KevinDiao.MySectionDemo01.MySectionGroup,KevinDiao.MySectionDemo01">
3: <section name="myBlog" type="KevinDiao.MySectionDemo01.MySection,KevinDiao.MySectionDemo01"/>
4: </sectionGroup>
5: </configSections>
6:
7: <myBlogs>
8: <myBlog name="五香瓜子" url="http://www.cnblogs.com/diaojia/"></myBlog>
9: </myBlogs>
读取web.config中配置:
1: MySection mySection = ConfigurationManager.GetSection("myBlogs/myBlog") as MySection;
2: Response.Write("博客名称:" + mySection.BlogName + "<br/>");
3: Response.Write("博客地址:<a href=" + mySection.BlogUrl + ">" + mySection.BlogUrl + "</a>");
运行得到的结果:
博客名称:五香瓜子
博客地址:http://www.cnblogs.com/diaojia/
2、ConfigurationElementCollection的使用
--------------------------------------------------------------------------------
下面再来讨论一下怎么在ConfigSections中配置自定义集合,我们还是用代码说明吧。
1)、 首先定义一个继承ConfigurationElement的类。
1: /// <summary>
2: /// 自定义Element
3: /// </summary>
4: public class MyBlogElement:ConfigurationElement
5: {
6: [ConfigurationProperty("name")]
7: public string Name
8: {
9: get
10: {
11: return (string)base["name"];
12: }
13: }
14: [ConfigurationProperty("url")]
15: public string Url
16: {
17: get
18: {
19: return (string)base["url"];
20: }
21: }
22: }
它主要包含要配置的主要内容。
2)、其次定义一个继承ConfigurationElementCollection的类
1: /// <summary>
2: /// 自定义ElementCollection
3: /// </summary>
4: public class MyBlogElementCollection:ConfigurationElementCollection
5: {
6: &n
补充:Web开发 , ASP.Net ,