【问题标题】:How to create custom web config?如何创建自定义 Web 配置?
【发布时间】:2015-04-28 15:44:10
【问题描述】:

我需要在 web.config 文件中创建一个配置部分。配置部分如下所示。

<component name="name1" title="title1" description="description1"/>
<component name="name2" title="title2" description="description2"/>
<component name="name3" title="title3" description="description3"/>

如何创建这样的配置设置以及如何在 c# 代码中访问配置中的属性。

【问题讨论】:

    标签: c# .net web-config


    【解决方案1】:

    1) 创建一个类并继承自ConfigurationSection

    public class ComponentCustomSection : ConfigurationSection
    

    2) 添加属性并使用 ConfigurationProperty 属性对其进行标记

            [ConfigurationProperty("name")]
            public string Name
            {
                get { return ((string)this["name"]); }
            }
    
            [ConfigurationProperty("title")]
            public string Title
            {
                get { return ((string)this["title"]); }
            }
    
            [ConfigurationProperty("description")]
            public string Description
            {
                get { return ((string)this["description"]); }
            }
    

    3) 在配置文件中添加自定义配置部分的信息(在配置标签下)

      <configSections>
        <section name="component" type="YourAssembly.ComponentCustomSection, YourAssembly"/>
      </configSections>
    

    4)您可以使用以下代码获取该部分

    var section = ConfigurationManager.GetSection("component")
    

    请注意,这适用于单个组件标记。
    如果你需要有N个标签,你应该把它们封装在一个父标签中,像这样

    <components>
        <component name="name1" title="title1" description="description1"/>
        <component name="name2" title="title2" description="description2"/>
        <component name="name3" title="title3" description="description3"/>
    </components>
    

    Here 是一篇很好的文章,可帮助您开始自定义配置部分

    Here 是一个关于有一个带有子元素的 customSection 应该可以帮助你的问题

    【讨论】:

    • 我试过这个。但是我如何从代码中的配置中获取值。因为有多个属性和多个组件
    • 看我的编辑,如果你需要多个标签,你必须封装它们
    • 脱帽致敬..我在互联网上获得的第一个分步回答..您的多个标签链接也帮助了我很多..你让我开心..非常感谢:)
    • @CSharper 没问题,很高兴我能帮上忙
    猜你喜欢
    • 2011-02-26
    • 1970-01-01
    • 1970-01-01
    • 2011-11-21
    • 2015-06-08
    • 1970-01-01
    • 2010-10-21
    • 1970-01-01
    • 2011-02-02
    相关资源
    最近更新 更多