无法识别的属性&#39; name&#39;在ConfigurationElementCollection中使用<remove>时

时间:2018-04-05 16:41:40

标签: configuration configuration-files configurationsection

我有一个自定义ConfigurationSection,其中包含带有自定义ConfigurationElementCollection个实例的自定义ConfigurationElement<add><clear>标记在配置文件中正常工作,但在我的单元测试期间使用<remove>会生成以下异常:

System.Configuration.ConfigurationErrorsException:无法识别的属性&#39; name&#39;。请注意,属性名称区分大小写。

配置文件非常简单。这是测试部分的内部部分:

<exceptionHandling>
  <policies>
    <clear />
    <add name="default" shouldLog="true" shouldShow="true"/>
    <add name="initialization" shouldLog="true" shouldShow="true"/>
    <add name="security" shouldLog="true" shouldShow="true"/>
    <add name="logOnly" shouldLog="true" shouldShow="false"/>
    <add name="unhandled" shouldLog="true" shouldShow="true"/>
    <add name="test" shouldLog="false" shouldShow="false"/>
    <remove name="test"/>
  </policies>
</exceptionHandling>

以下是配置类的相关代码(为简洁起见,有些代码已被省略)。

public sealed class ExceptionHandlingSection : ConfigurationSection
{
    [ConfigurationProperty("policies", IsDefaultCollection = false)]
    [ConfigurationCollection(typeof(PolicyElementCollection), AddItemName = "add", RemoveItemName = "remove", ClearItemsName = "clear")]
    public PolicyElementCollection Policies => (PolicyElementCollection)base["policies"];
}

public sealed class PolicyElementCollection : ConfigurationElementCollection
{
   // pretty boiler plate
}

public sealed class PolicyElement : ConfigurationElement
{
    [ConfigurationProperty("name", IsRequired = true)]
    public string Name
    {
        get => (string)this["name"];
        set => this["name"] = value;
    }

    // other properties
}

需要做些什么才能使<remove>工作,如测试配置文件中所示?

1 个答案:

答案 0 :(得分:0)

答案很简单。

我读了一些关于XML属性的内容,但从根本上说它正在寻找一个关键属性。这可以由ConfigurationPropertyAttribute的属性指定。要让<remove>标记生效,我需要做的就是更改我的ConfigurationElement类,如下所示:

public sealed class PolicyElement : ConfigurationElement
{
    [ConfigurationProperty("name", IsKey = true, IsRequired = true)]
    public string Name
    {
        get => (string)this["name"];
        set => this["name"] = value;
    }

    // other properties
}