ConfigurationValidatorBase 验证方法接收默认值

ConfigurationValidatorBase validate method receives default value

我正在尝试构建 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,所有传递给 class FloatValidator 中的 Validate() 的值都是 0,所以我实际上无法验证输入。

提前致谢

似乎有效。

使用这个 app.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="CompoundConfiguration" type="ConsoleApplication2.CompoundConfigurationSection,ConsoleApplication2,Version=1.0.0.0,Culture=neutral,PublicKeyToken=null"  />
  </configSections>  
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
    </startup>
  <CompoundConfiguration>
    <Compounds>
      <add name="Particles smaller than 10 µm, Tapered Element Oscillating Microbalance measurement" abbreviation="PM10Teom" id="161" factor="1" />
      <add name="Ozone" abbreviation="O3" id="147" factor="1.9957" />
    </Compounds>
  </CompoundConfiguration>
</configuration>

并提供 ConfigurationSection 的实现:

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"];
        }
    }
}

与 ElementCollection 一起:

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);
    }
}

运行这条主线:

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

给出异常消息:

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

我猜哪个是预期结果?

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

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

您应该为 Factor 提供默认值:

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

用于 Id-属性 的内置 IntegerValidator 属性实际上也是如此。如果您使用不包含零的范围,并且不应用默认值,它将无法验证。参见 。