本文介绍了在意外的ConfigurationProperty失败RegexStringValidator定制的ConfigurationElement的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写我自己的自定义配置部分,并在的ConfigurationElement定义,像这样一个的ConfigurationProperty:

I am writing my own custom configuration section and have a ConfigurationProperty defined in a ConfigurationElement like so:

[ConfigurationProperty("startTime", IsRequired = false)]
[RegexStringValidator("\\d{2}:\\d{2}:\\d{2}")]
public string StartTime
{
    get
    {
        return (string) this["startTime"];
    }

    set
    {
        this["startTime"] = value;
    }
}



我期待着能够进入的值,如在我创建了的ConfigurationElement的属性的startTime23:30:00。但是,每当我尝试加载我的配置部分,我得到的消息是ConfigurationErrorsException:

I am expecting to be able to enter values such as "23:30:00" in the startTime attribute of the ConfigurationElement that I have created. However, whenever I try to load my configuration section, I get an ConfigurationErrorsException with the message:

有关财产的startTime'的值无效。错误是:值不符合验证正则表达式字符串'\d {2}:\d {2}:\d {2}。

我承认我总是用正则表达式挣扎,但是这一次是很简单,我写了一个测试,以验证我的模式应该验证该种我期待值:

I'll admit I always struggle with regular expressions, but this one is simple enough and I wrote a test to verify that my pattern should validate the kinds of values I am expecting:

var regex = new Regex(@"\d{2}:\d{2}:\d{2}", RegexOptions.Compiled);
var isSuccess = regex.Match("23:30:00").Success;



isSuccess计算结果为True,所以我不太清楚为什么ConfigurationErrorsException被抛出。

isSuccess evaluates to True, so I am not quite sure why the ConfigurationErrorsException is being thrown.

作为参考,这是我的配置节从我App.config文件:

As a reference, here is my configuration section from my App.config file:

<windowsServiceConfiguration>
  <schedule startTime = "23:00:00" />
</windowsServiceConfiguration>



任何帮助,为什么我不能得到RegexStringValidator工作将不胜感激。谢谢

Any help as to why I can't get the RegexStringValidator to work would be appreciated. Thanks.

推荐答案

尝试定义的默认值,将通过验证:

Try to define the default value that will pass the validation:

[ConfigurationProperty("startTime", IsRequired = false, DefaultValue = "00:00:00")]
[RegexStringValidator(@"\d{2}:\d{2}:\d{2}")]
public string StartTime
{
    get 
    {
        return (string) this["startTime"];
    }

    set
    {
        this["startTime"] = value;
    }
}

这篇关于在意外的ConfigurationProperty失败RegexStringValidator定制的ConfigurationElement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 01:04