Sea*_*ugh 14 c# asp.net configuration
我通过继承来在ac#类库中创建了一个自定义配置部分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文件中有有效值,我也会收到此错误.如果我删除验证器,它可以完美地工作.有谁知道怎么解决这个问题?
我能够通过使用显式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配置元素类反映的代码紧密建模的。我仍然希望不必重复我的验证,但至少这段代码允许我指定一个空白默认值,同时仍然需要一个值进入。)
| 归档时间: | 
 | 
| 查看次数: | 3762 次 | 
| 最近记录: |