我有一个包含以下内容的类 ConfigurationSection :
namespace DummyConsole {
class TestingComponentSettings: ConfigurationSection {
[ConfigurationProperty("waitForTimeSeconds", IsRequired=true)]
[IntegerValidator(MinValue = 1, MaxValue = 100, ExcludeRange = false)]
public int WaitForTimeSeconds
{
get { return (int)this["waitForTimeSeconds"]; }
set { this["waitForTimeSeconds"] = value; }
}
[ConfigurationProperty("loginPage", IsRequired = true, IsKey=false)]
public string LoginPage
{
get { return (string)this["loginPage"]; }
set { this["loginPage"] = value; }
}
}
}
然后我的 .config 文件中有以下内容:
<configSections>
<section name="TestingComponentSettings"
type="DummyConsole.TestingComponentSettings, DummyConsole"/>
</configSections>
<TestingComponentSettings waitForTimeSeconds="20" loginPage="myPage" />
然后,当我尝试使用此配置部分时,出现以下错误:
var Testing = ConfigurationManager.GetSection("TestingComponentSettings")
as TestingComponentSettings;
ConfigurationErrorsException was unhandled
The value for the property 'waitForTimeSeconds' is not valid. The error is: The value must be inside the range 1-100.
如果我将 IntegerValidator
更改为 ExcludeRage = true,我(显然)得到:
ConfigurationErrorsException was unhandled
The value for the property 'waitForTimeSeconds' is not valid. The error is: The value must not be in the range 1-100
如果我随后将 .config 中的属性值更改为大于 100 的数字,它就会起作用。
如果我将验证器更改为只有 100 的 MaxValue
它会起作用,但也会接受 -1 的值。
是否可以在这样的范围内使用 IntegerValidatorAttribute
?
编辑添加
确认为 issue by Microsoft .
最佳答案
作为Skrud指出,MS 已经更新了连接问题:
The reported issue is because of a quirk in how the configuration system handles validators. Each numeric configuration property has a default value - even if one is not specified. When a default is not specified the value 0 is used. In this example the configuration property ends up with a default value that is not in the valid range specified by the integer validator. As a result configuration parsing always fails.
To fix this, change the configuration property definition to include a default value that is within the range of 1 to 100:
[ConfigurationProperty("waitForTimeSeconds", IsRequired=true, DefaultValue="10")]
这确实意味着该属性将有一个默认值,但我实际上并不认为这是一个主要问题 - 我们说它的值应该在“合理”范围内,并且应该做好准备设置合理的默认值。
关于c# - 我可以在自定义 ConfigurationSection 上使用 IntegerValidator 属性指定范围吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2109502/