问题描述
我已经从配置节
继承创建一个C#类库自定义配置节。我引用类库在我的web应用程序(也C#,ASP.NET),填写相应的属性,一切的伟大工程。当我开始添加验证问题开始。
I have created a custom configuration section in a c# class library by inheriting from ConfigurationSection
. I reference the class library in my web application (also c#, ASP.NET), fill in the appropriate attributes and everything works great. The problem starts when I start adding validators.
例如,此属性:
[ConfigurationProperty("appCode", IsRequired = true)]
public string ApplicationCode
{
get
{
return (string)base["appCode"];
}
set
{
base["appCode"] = value;
}
}
正如它工作正常,但只要我补充一点:
As is it works fine, but as soon as I add this:
[StringValidator(MinLength=1)]
它的炸弹,出现以下错误:
It bombs with the following error:
的的属性appCode'的值无效。错误是:该字符串必须至少有1个字符的
我得到这个错误,即使一个有效的 appCode
值是在我的的web.config
文件。如果我删除了验证它完美。有谁知道如何解决这个问题?
I get this error even though a valid appCode
value is in my web.config
file. If I remove the validator it works perfectly. Does anyone know how to get around this?
推荐答案
我是能够通过使用显式的为重点,以我的属性集合,而不是一个字符串,按以下实现:
I was able to work around this issue by using an explicit ConfigurationProperty as the key to my properties collection rather than a string, as per the following implementation:
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; }
}
}
(此代码贴切地反映代码为蓝本从配置元素类。我仍然希望我没有重复我的验证,但至少这段代码可以让我指定一个空白的默认值,同时还要求要输入一个值。)
(This code is closely modeled after the code reflected from the AssemblyInfo configuration element class. I still wish I didn't have to duplicate my validations, but at least this code allows me to specify a blank default value while still requiring a value to be entered.)
这篇关于为什么总是StringValidator失败的自定义配置节?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!