2010-01-21 74 views
6

我有一个包含一个类中的下列ConfigurationSection我可以在自定义ConfigurationSection上使用IntegerValidator属性指定范围吗?

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.

如果我陈GE的IntegerValidator有一个ExcludeRage =真,我(显然)获得:

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的属性的值,它的工作原理。

如果我将验证器更改为只有一个MaxValue为100,它可以工作,但也会接受值-1。

有没有可能像这样使用IntegerValidatorAttribute

编辑补充

确认为issue by Microsoft

+2

微软链接今天已经更新了一个解决方案。显然,如果没有指定默认值,它将使用“0”作为默认值。当然,0在1-100的范围之外。 “解决方案”是将DefaultValue =参数添加到ConfigurationProperty属性,并使用默认值在该范围内。不幸的是,这意味着你正在强加一个默认值,这可能不是你想要的或者需要的。 我一直有这个问题了。很高兴我偶然发现了这个问题! – Skrud 2010-01-27 21:12:09

回答

13

由于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")] 

这并不意味着房地产将有一个默认的,但我真的不认为这是一个重大问题 - 我们说它应该具有属于“明智”范围的价值,并且应该准备设置合理的违约。

+3

这是什么结束了为我工作。在我的情况下,我特别想要在配置文件中指定选项,所以我不想设置默认值。但是,事实证明,如果您将某个字段标记为必需,则事实优先,并且默认值永远不会被_used_使用,除非保持验证不被过早触发。这有点反直觉,但它的工作原理。 – 2014-05-07 21:31:24

+0

很高兴认识威廉,谢谢 – 2014-05-07 21:40:38

相关问题