简体   繁体   English

自定义配置部分的问题

[英]Problems with custom config section

I am trying to make a fairly simple custom configuration section.我正在尝试制作一个相当简单的自定义配置部分。 My class is:我的班级是:

namespace NetCenterUserImport
{
    public class ExcludedUserList : ConfigurationSection
    {
        [ConfigurationProperty("name")]
        public string Name
        {
            get { return (string)base["name"]; }
        }

        [ConfigurationProperty("excludedUser")]
        public ExcludedUser ExcludedUser
        {
            get { return (ExcludedUser)base["excludedUser"]; }
        }

        [ConfigurationProperty("excludedUsers")]
        public ExcludedUserCollection ExcludedUsers
        {
            get { return (ExcludedUserCollection)base["excludedUsers"]; }
        }
   }

   [ConfigurationCollection(typeof(ExcludedUser), AddItemName = "add")]
   public class ExcludedUserCollection : ConfigurationElementCollection
    {
        protected override ConfigurationElement CreateNewElement()
        {
            return new ExcludedUserCollection();
        }

        protected override object GetElementKey(ConfigurationElement element)
        {
            return ((ExcludedUser)element).UserName;
        }
    }

    public class ExcludedUser : ConfigurationElement
    {
        [ConfigurationProperty("name")]
        public string UserName
        {
            get { return (string)this["name"]; }
            set { this["name"] = value; }
        }
    }
}

My app.config is:我的 app.config 是:

  <excludedUserList name="test">
<excludedUser name="Hello" />
<excludedUsers>
  <add name="myUser" />
</excludedUsers>

When I attempt to get the custom config section using:当我尝试使用以下方法获取自定义配置部分时:

var excludedUsers = ConfigurationManager.GetSection("excludedUserList");

I get an exception saying我得到一个例外说

"Unrecognized attribute 'name'." “无法识别的属性 'name'。”

I'm sure I'm missing something simple, but I've looked at a dozen examples and answers on here and can't seem to find where I'm going wrong.我确定我遗漏了一些简单的东西,但我在这里看了十几个例子和答案,似乎找不到我哪里出错了。

In ExcludedUserCollection.CreateNewElement method you are creating a ExcludedUserCollection instance, it should be a single element such as:在 ExcludedUserCollection.CreateNewElement 方法中,您正在创建一个 ExcludedUserCollection 实例,它应该是单个元素,例如:

protected override ConfigurationElement CreateNewElement()
{
    return new ExcludedUser();
}

Changing the method as above worked for me.更改上述方法对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM