ConfigurationValidatorBase validate方法接收默认值

时间:2016-09-06 12:13:10

标签: c# .net validation web-config

我正在尝试构建一个FloatValidatorAttribute。 在这篇msdn文章中:https://msdn.microsoft.com/en-us/library/system.configuration.configurationvalidatorattribute(v=vs.110).aspx

有一些例子。 " ProgrammableValidator"并且它的属性示例是我想要的浮点验证器。

我在这个网站上找到的唯一相关的问题是这个未解决的问题: Validation of double using System.Configuration validator

我也发现了这个:https://social.msdn.microsoft.com/Forums/vstudio/en-US/6faf9c70-162c-499b-8d0c-0b1f19c7a24a/issues-with-custom-configuration-validator-and-attribute?forum=clr 那个人听起来像我一样的问题。但它对我没有帮助

我的问题是web.config中的值未正确传递给我创建的FloatValidator的Validate方法。

这是我的代码:

class FloatValidator : ConfigurationValidatorBase
{
    public float MinValue { get; private set; }
    public float MaxValue { get; private set; }

    public FloatValidator(float minValue, float maxValue)
    {
        MinValue = minValue;
        MaxValue = maxValue;
    }

    public override bool CanValidate(Type type)
    {
        return type == typeof(float);
    }

    public override void Validate(object obj)
    {
        float value;
        try
        {
            value = float.Parse(obj.ToString());
        }
        catch (Exception)
        {
            throw new ArgumentException();
        }

        if (value < MinValue)
        {
            throw new ConfigurationErrorsException($"Value too low, minimum value allowed: {MinValue}");
        }

        if (value > MaxValue)
        {
            throw new ConfigurationErrorsException($"Value too high, maximum value allowed: {MaxValue}");
        }
    }
}

它自己的属性:

class FloatValidatorAttribute : ConfigurationValidatorAttribute
{
    public float MinValue { get; set; }
    public float MaxValue { get; set; }

    public FloatValidatorAttribute(float minValue, float maxValue)
    {
        MinValue = minValue;
        MaxValue = maxValue;
    }

    public override ConfigurationValidatorBase ValidatorInstance => new FloatValidator(MinValue, MaxValue);
}

配置元素:

public class Compound : ConfigurationElement
{
    [ConfigurationProperty("name", IsRequired = true, IsKey = true)]
    public string Name => this["name"] as string;

    [ConfigurationProperty("abbreviation", IsRequired = true)]
    public string Abbreviation => this["abbreviation"] as string;

    [ConfigurationProperty("id", IsRequired = true)]
    [IntegerValidator(ExcludeRange = false, MinValue = 0, MaxValue = int.MaxValue)]
    public int Id => (int)this["id"];

    [ConfigurationProperty("factor", IsRequired = true)]
    [FloatValidator(float.Epsilon, float.MaxValue)]
    public float Factor => (float) this["factor"];
}

以下是web.config

中复合元素的示例
    <add name="Ozone" abbreviation="O3" id="147" factor="1.9957"/>
    <add name="Particles smaller than 10 µm, Tapered Element Oscillating Microbalance measurement" abbreviation="PM10Teom" id="161" factor="1" />

我可以正确检索值,并且可以将因子应用于我正在进行的测量。 但是如果我应用FloatValidator,FloatValidator类中传递给Validate()的所有值都是0,所以我实际上无法验证输入。

提前谢谢

2 个答案:

答案 0 :(得分:1)

该框架似乎正在验证您的属性的默认值。由于不存在默认值,因此使用default(float)。这就是为什么你看到调用Validate传递0的原因。

由于您的验证失败,因此您看不到后续调用。它们将包含您配置中的相关值。

您应该为Factor提供默认值:

[ConfigurationProperty("factor", IsRequired = true, DefaultValue = float.Epsilon)]

用于IntegerValidator - 属性的内置Id - 属性实际上也是如此。如果您使用的范围不包含零,并且不应用默认值,则不会验证。请参阅https://stackoverflow.com/a/2150643/1668425

答案 1 :(得分:0)

似乎有效。

使用此app.config:

public class CompoundConfigurationSection : ConfigurationSection
{
    [ConfigurationProperty("Compounds", IsDefaultCollection = false)]
    [ConfigurationCollection(typeof(CompoundCollection),
        AddItemName = "add",
        ClearItemsName = "clear",
        RemoveItemName = "remove")]
    public CompoundCollection Compounds
    {
        get
        {
            return (CompoundCollection)base["Compounds"];
        }
    }
}

提供ConfigurationSection的实现:

public class CompoundCollection : ConfigurationElementCollection
{
    public CompoundCollection()
    {
    }

    public Compound this[int index]
    {
        get { return (Compound)BaseGet(index); }
        set
        {
            if (BaseGet(index) != null)
            {
                BaseRemoveAt(index);
            }
            BaseAdd(index, value);
        }
    }

    public void Add(Compound serviceConfig)
    {
        BaseAdd(serviceConfig);
    }

    public void Clear()
    {
        BaseClear();
    }

    protected override ConfigurationElement CreateNewElement()
    {
        return new Compound();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        return ((Compound)element).Id;
    }

    public void Remove(Compound serviceConfig)
    {
        BaseRemove(serviceConfig.Id);
    }

    public void RemoveAt(int index)
    {
        BaseRemoveAt(index);
    }

    public void Remove(string name)
    {
        BaseRemove(name);
    }
}

与ElementCollection一起使用:

    static void Main(string[] args)
    {
        var compounds = ConfigurationManager.GetSection("CompoundConfiguration");
    }

运行此主程序:

Value too low, minimum value allowed: 1,401298E-45

给出了一条消息:

{{1}}

我猜是预期的结果?