自定义ConfigurationElement属性验证失败

使用自己创建的ConfigurationElement时,一个字符串属性Name无法验证通过导致Element无法被构造,属性定义如下:

[ConfigurationProperty("name", IsRequired = true)] [StringValidator(InvalidCharacters = "~!@#$%^&*()[]{}/;'\"|\\", MinLength = 1, MaxLength = 60)] public string Name { get { return (string)this["name"]; } set { this["name"] = value; } }

错误提示是"The value for the property 'name' is not valid. The error is: The string must be at least 1 characters long."当然事实上在config文件中定义的name值是满足条件的。

原因在于ConfigurationElement对象构造时,会首先用默认值来初始化各个属性,而这个默认值同样会接受validator的检验。这里的默认值是string.Empty,所以当然不满足条件了。

解决办法是为ConfigurationPropertyAttribute设置DefaultValue:

[ConfigurationProperty("name", DefaultValue = "unnamed", IsRequired = true)] [StringValidator(InvalidCharacters = "~!@#$%^&*()[]{}/;'\"|\\", MinLength = 1, MaxLength = 60)] public string Name { get { return (string)this["name"]; } set { this["name"] = value; } }

同时由于这个属性是必须的(IsRequired = true),所以也不必担心默认值会真的被使用。

 

参考:

http://msdn.microsoft.com/en-us/library/system.configuration.configurationproperty(VS.85).aspx#1

 

此处指出了另一种可行的办法,而不必提供一个无用的默认值:

http://stackoverflow.com/questions/3744953/why-does-configurationvalidator-validate-the-default-value-of-a-configurationprop

 

另外附上一些关于Configuration的网页:

http://www.codeproject.com/KB/dotnet/mysteriesofconfiguration.aspx

http://www.codeproject.com/KB/dotnet/mysteriesofconfiguration2.aspx

Creating a Custom Configuration Section in C#

posted on 2011-01-13 03:01  Gildor Wang  阅读(894)  评论(0编辑  收藏  举报

导航