.net IConfigurationSectionHandler接口应用

.net 自定义WebConfig中的节点,方法如下:
1、创建自定义节点类CompanySection。该类中的属性(Path、CompanyName、IsPrivate)与WebConfig中的自定义节点名称对应。
namespace Test
{
    public class CompanySection
    {
        private string _path = "";
        private string _companyName = "";
        private bool _isPrivate = false;

        public string Path
        {
            get { return _path; }
            set { _path = value; }
        }

        public string CompanyName
        {
            get { return _companyName; }
            set { _companyName = value; }
        }

        public bool IsPrivate
        {
            get { return _isPrivate; }
            set { _isPrivate = value; }
        }
    }
}
2、创建类CompanySectionHandler。该类继承IConfigurationSectionHandler接口并实现Create()方法
namespace Test
{
    public class CompanySectionHandler : IConfigurationSectionHandler
    {
        public object Create(object parent, object configContext, XmlNode section)
        {
            CompanySection para = new CompanySection();//自定义节点类

            foreach (XmlNode xn in section.ChildNodes)
            {
                switch (xn.Name)
                {
                    case "path":
                        para.Path = xn.SelectSingleNode("@value").InnerText;
                        break;
                    case "companyName":
                        para.CompanyName = xn.SelectSingleNode("@value").InnerText;
                        break;
                    case "isPrivate":
                        para.IsPrivate = bool.Parse(xn.SelectSingleNode("@attribute").InnerText);
                        break;
                }
            }
            return para;
        }
    }
}
3、配置WebConfig。在<configuration>节点下增加如下节点
<configuration>
  <configSections>
    <sectionGroup name ="CompanyGroups">
      <section name ="CompanySection" type ="Test.CompanySectionHandler,Test"/>
    </sectionGroup>
  </configSections>

  <CompanyGroups>
    <CompanySection>
      <path value="NONE"/>
      <companyName value="Robsun"/>
      <isPrivate attribute="true"/>
    </CompanySection>
  </CompanyGroups>

 <system.web>
</system.web>
</configuration>
4、调用
protected void Page_Load(object sender, EventArgs e)
    {
        Test.CompanySection para =
            ConfigurationManager.GetSection("CompanyGroups/CompanySection") as Test.CompanySection;

        Response.Write("CompanyName: " + para.CompanyName + "<br>");
        Response.Write("Path: " + para.Path + Environment.NewLine + "<br>");
        Response.Write("isPrivate: " + para.IsPrivate.ToString() + "<br>");

    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值