c# - 为什么自定义配置部分的 StringValidator 总是失败?

标签 c# asp.net configuration

我通过继承 ConfigurationSection 在 c# 类库中创建了一个自定义配置部分。我在我的 Web 应用程序(也包括 C#、ASP.NET)中引用类库,填写适当的属性,一切正常。当我开始添加验证器时,问题就开始了。

例如,这个属性:

    [ConfigurationProperty("appCode", IsRequired = true)]
    public string ApplicationCode
    {
        get
        {
            return (string)base["appCode"];
        }
        set
        {
            base["appCode"] = value;
        }
    }

因为它工作正常,但是一旦我添加这个:

    [StringValidator(MinLength=1)]  

它因以下错误而爆炸:

属性“appCode”的值无效。错误是:字符串必须至少有 1 个字符长。

即使我的 web.config 文件中有一个有效的 appCode 值,我也会收到此错误。如果我删除验证器,它会完美运行。有谁知道如何解决这个问题?

最佳答案

我能够通过使用显式 ConfigurationProperty 来解决这个问题作为我的属性集合的键而不是字符串,按照以下实现:

public class AssemblyElement : ConfigurationElement
{
    private static readonly ConfigurationProperty _propAssembly;
    private static readonly ConfigurationPropertyCollection _properties;

    static AssemblyElement()
    {
        _propAssembly = new ConfigurationProperty("assembly", typeof(string), null, null, new StringValidator(1), ConfigurationPropertyOptions.IsKey | ConfigurationPropertyOptions.IsRequired);
        _properties = new ConfigurationPropertyCollection();
        _properties.Add(_propAssembly);
    }

    internal AssemblyElement() { }
    public AssemblyElement(string assemblyName)
    {
        this.Assembly = assemblyName;
    }

    [ConfigurationProperty("assembly", IsRequired = true, IsKey = true, DefaultValue = "")]
    [StringValidator(MinLength = 1)]
    public string Assembly
    {
        get { return (string)base[_propAssembly]; }
        set { base[_propAssembly] = value; }
    }

    internal AssemblyName AssemblyName
    {
        get { return new AssemblyName(this.Assembly); }
    }

    protected override ConfigurationPropertyCollection Properties
    {
        get { return _properties; }
    }
}

(此代码与 AssemblyInfo 配置元素类反射(reflect)的代码密切相关。我仍然希望我不必重复验证,但至少此代码允许我指定空白默认值,同时仍然需要输入一个值。)

关于c# - 为什么自定义配置部分的 StringValidator 总是失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3585407/

相关文章:

c# - Json 序列化将 k__BackingField 添加到我的属性

c# - 如何从 ASP.NET Web API ValueProvider 中的 HTTP POST 请求检索正文值?

configuration - OpenLiberty 无法注入(inject)环境变量

asp.net - ReportViewer 2012 是否与用于远程访问的 SSRS Server 2005 兼容?

asp.net - Visual Studio 2008 将 asp 标签格式化为小写

eclipse - 没有加载 apache-tomcat-8.0.17 的管理器/html

java - 使用 Hibernate 配置 c3p0 属性 initialPoolSize 和 maxStatements

c# - 何时使用 "async"而不是返回新的 Task.Run 任务?

c# - 将 ddMMyyyy 格式的字符串转换为 DateTime

c# - Silverlight C# 是否有将集合转换为文件以及相反的标准方法?