我可以在自定义ConfigurationSection上指定具有IntegerValidator属性的范围吗?

时间:2010-01-21 13:30:04

标签: c# asp.net validation configurationsection

我有一个包含以下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范围内。

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

  

ConfigurationErrorsException未处理

     

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

范围内

如果我然后将.config中的属性值更改为高于100的数字,则可以正常工作。

如果我将验证器更改为只有MaxValue为100,则它会起作用,但也会接受-1的值。

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

编辑以添加

确认为issue by Microsoft

1 个答案:

答案 0 :(得分:15)

正如Skrud所指出的,MS更新了连接问题:

  

报告的问题是由于配置系统如何处理验证器的怪癖。每个数字配置属性都有一个默认值 - 即使未指定一个。如果未指定默认值,则使用值0。在此示例中,配置属性最终使用的默认值不在整数验证程序指定的有效范围内。因此,配置解析总是失败。

     

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

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

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