8

我有一个包含以下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 未处理

属性“waitForTimeSeconds”的值无效。错误是:该值必须在 1-100 范围内。

如果我将其更改为IntegerValidatorExcludeRage = true,我(显然)会得到:

ConfigurationErrorsException 未处理

属性“waitForTimeSeconds”的值无效。错误是:该值不能在 1-100 范围内

如果我随后将 .config 中的属性值更改为大于 100 的数字,它就可以工作。

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

是否可以在IntegerValidatorAttribute这样的范围内使用?

编辑以添加

Microsoft确认为问题。

4

1 回答 1

16

正如Skrud指出的那样,MS 已经更新了连接问题:

报告的问题是由于配置系统处理验证器的方式存在问题。每个数字配置属性都有一个默认值——即使没有指定。如果未指定默认值,则使用值 0。在此示例中,配置属性以不在整数验证器指定的有效范围内的默认值结束。结果配置解析总是失败。

要解决此问题,请更改配置属性定义以包含 1 到 100 范围内的默认值:

[ConfigurationProperty("waitForTimeSeconds", IsRequired=true, 
                       DefaultValue="10")]

这确实意味着该属性将有一个默认值,但我实际上并不认为这是一个主要问题——我们说它应该有一个在“合理”范围内的值,并且应该准备好设置一个明智的默认。

于 2010-01-27T22:07:28.997 回答