我通过继承 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/