2010-01-21 55 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

相關問題