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

Zha*_*uid 8 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; }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

然后我在.config文件中有以下内容:

<configSections>
  <section name="TestingComponentSettings" 
           type="DummyConsole.TestingComponentSettings, DummyConsole"/>
</configSections>
<TestingComponentSettings waitForTimeSeconds="20" loginPage="myPage" />
Run Code Online (Sandbox Code Playgroud)

当我然后尝试使用此配置部分时,我收到以下错误:

var Testing = ConfigurationManager.GetSection("TestingComponentSettings")
             as TestingComponentSettings;
Run Code Online (Sandbox Code Playgroud)

ConfigurationErrorsException未处理

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

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

ConfigurationErrorsException未处理

属性"waitForTimeSeconds"的值无效.错误是:该值不得在1-100范围内

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

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

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

编辑添加

被微软确认为问题.

Zha*_*uid 16

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

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

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

[ConfigurationProperty("waitForTimeSeconds", IsRequired=true, 
                       DefaultValue="10")]
Run Code Online (Sandbox Code Playgroud)

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

  • 这就是最终为我工作的东西.在我的情况下,我特别想要在配置文件中指定选项,所以我不想设置默认值.但是,事实证明,如果您将字段标记为必需,则事实优先,默认值实际上从不_used_,以防止验证过早发生.这有点违反直觉,但它确实有效. (4认同)