使用<remove/>操作ConfigurationElementCollection时出现'Unrecognized attribute 'name''错误
解决自定义ConfigurationSection中标签报错的问题
这个问题我之前也踩过坑!本质是你的自定义ConfigurationElementCollection没有正确告诉.NET配置系统:哪个属性是集合元素的唯一标识键,所以解析<remove>标签时,系统识别不了name这个属性,就抛出了那个大小写敏感的错误。
核心原因
当你在配置里用<remove name="xxx">时,.NET配置框架需要知道集合中每个元素的「键属性」,才能定位到要移除的元素。如果你的自定义集合类没有正确指定这个键,系统就会把name当成一个未定义的属性,直接抛出异常。
解决方案(分两步)
1. 给自定义ConfigurationElement标记键属性
在你的自定义ConfigurationElement子类中,把作为唯一标识的属性(比如name)用[ConfigurationProperty]标记,并且设置IsKey = true,示例代码:
public class CustomElement : ConfigurationElement { // 关键:设置IsKey=true,告诉系统这是元素的唯一键 [ConfigurationProperty("name", IsRequired = true, IsKey = true)] public string Name { get => (string)this["name"]; set => this["name"] = value; } // 其他自定义属性示例 [ConfigurationProperty("value", IsRequired = false)] public string Value { get => (string)this["value"]; set => this["value"] = value; } }
2. 在ConfigurationElementCollection中重写GetElementKey方法
你的自定义集合类必须重写GetElementKey方法,返回刚才标记的键属性值,这样系统才能通过<remove>的name值找到对应的元素:
public class CustomElementCollection : ConfigurationElementCollection { protected override ConfigurationElement CreateNewElement() { return new CustomElement(); } // 关键:返回元素的键属性,和上面的IsKey配置对应 protected override object GetElementKey(ConfigurationElement element) { return ((CustomElement)element).Name; } }
配置文件的正确写法
确保<remove>的属性名和你代码中ConfigurationProperty的name参数完全一致(注意大小写!):
<customSection> <customElements> <add name="TestElement" value="123" /> <!-- 这里的name要和代码里的ConfigurationProperty名称完全匹配 --> <remove name="TestElement" /> <clear /> </customElements> </customSection>
额外注意事项
- 如果你的集合类重写了
IsElementName方法,要确保它能正确识别<remove>标签,不过默认实现已经处理了这个逻辑,一般不需要额外修改。 - 严格注意大小写:代码中
ConfigurationProperty的第一个参数(比如"name")要和配置里的属性名完全一致,比如代码里写"Name"(首字母大写),配置里用name就会触发大小写敏感的报错。
内容的提问来源于stack exchange,提问作者Anthony T.
相关产品推荐
相关产品推荐

