我通过继承在 C# 类库中创建了一个自定义配置部分ConfigurationSection
。我在 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 个字符。
即使有效,我也会收到此错误appCode
价值在我的web.config
文件。如果我删除验证器,它就可以正常工作。有谁知道如何解决这个问题?
我能够通过使用显式的方法来解决这个问题配置属性 http://msdn.microsoft.com/en-us/library/system.configuration.configurationproperty.aspx作为我的属性集合的键而不是字符串,按照以下实现:
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; }
}
}
(此代码是根据从装配信息 http://msdn.microsoft.com/en-us/library/system.web.configuration.assemblyinfo.aspx配置元素类。我仍然希望不必重复验证,但至少此代码允许我指定空白默认值,同时仍需要输入值。)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)