问题
I have a class containing the following 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; }
}
}
}
I then have the following in my .config file:
<configSections>
<section name="TestingComponentSettings"
type="DummyConsole.TestingComponentSettings, DummyConsole"/>
</configSections>
<TestingComponentSettings waitForTimeSeconds="20" loginPage="myPage" />
When I then attempt to use this configuration section I get the following error:
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.
If I change the IntegerValidator
to have an ExcludeRage = true, I (obviously) get:
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
If I then change the value of the property in the .config to a number higher than 100, it works.
If I change the validator to just have a MaxValue
of 100 it works, but will also accept a value of -1.
Is it possible to use the IntegerValidatorAttribute
with a range like this?
Edit to add
Confirmed as an issue by Microsoft.
回答1:
As Skrud points out, MS have updated the connect issue:
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")]
This does mean that the property will have a default, but I don't actually see that as a major issue - we're saying that it should have a value that falls within a "sensible" range, and should be prepared to set a sensible default.
来源:https://stackoverflow.com/questions/2109502/can-i-specify-a-range-with-the-integervalidator-attribute-on-a-custom-configurat