c# - 我可以在自定义 ConfigurationSection 上使用 IntegerValidator 属性指定范围吗?

标签 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 was unhandled

The value for the property 'waitForTimeSeconds' is not valid. The error is: The value must be inside the range 1-100.

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

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 的数字,它就会起作用。

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

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

编辑添加

确认为 issue by Microsoft .

最佳答案

作为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")]

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

关于c# - 我可以在自定义 ConfigurationSection 上使用 IntegerValidator 属性指定范围吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2109502/

相关文章:

ASP.Net session 在回发后偶尔会丢失

javascript 表单验证,在提交帮助之前?

javascript - jquery 验证插件 textarea

javascript - 如何通过 Angular 指令管理表单有效性?

c# - 霍夫变换问题

c# - 如何在 macOS 上运行 Windows 窗体应用程序?

c# - 验证错误后如何保存文件上传?

java - 接口(interface)泛型重载

c# - 映射无法正常工作 (ASP.NET)

asp.net - Treeview 检查的节点未按顺序返回