【问题标题】:Read an attribute "type" from a custom <section> node in web.config从 web.config 中的自定义 <section> 节点读取属性“类型”
【发布时间】:2013-06-03 17:55:42
【问题描述】:

我在 web.config 中定义了自己的

元素。

我需要通过自定义

指定的参数之一是类型。

例如,我目前有

<variable name="stage" value="dev" type="System.String, mscorlib" />

然后在我的ConfigurationElement 的实现中我有

[ConfigurationProperty("type", IsRequired = true)]
public Type ValueType
{
    get
    {
        var t = (String) this["type"];
        return Type.GetType(t);
    }
    set
    {
        this["type"] = value;
    }
}

在运行时会抛出异常

找不到支持“类型”类型的属性“类型”转换为/从字符串转换的转换器。

我尝试过各种方法,例如

  • 将属性重命名为valueType(以避免与可能的同名预配置属性发生冲突)
  • 将其简单地指定为"System.String"
  • 将属性中的getter更改为return (Type) this["type"];

但例外总是一样的。

有人能指出正确的方向吗?

【问题讨论】:

    标签: asp.net types web-config configsection


    【解决方案1】:

    使用这样的东西:

    [ConfigurationProperty("type", IsRequired = true)]
    [TypeConverter(typeof(TypeNameConverter)), SubclassTypeValidator(typeof(MyBaseType))]
    public Type ValueType
    {
        get
        {
            return (Type)this["type"];            
        }
        set
        {
            this["type"] = value;
        }
    }
    

    SubclassTypeValidator 的使用不是绝对必要的,但大多数时候你会使用它……至少我会使用它。

    【讨论】:

      猜你喜欢
      • 2020-01-01
      • 2017-11-01
      • 2019-12-10
      • 2022-11-21
      • 2021-07-19
      • 2015-09-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-10
      相关资源
      最近更新 更多