asp.nettypesweb-configconfigsection

Read an attribute "type" from a custom <section> node in web.config


I've defined my own <sectionGroup> and <section> elements in the web.config.

One of the parameters that I need to specify via my custom <section> is a Type.

For example, I currently have

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

and then in my implementation of ConfigurationElement I have

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

At runtime this throws the exception

Unable to find a converter that supports conversion to/from string for the property 'type' of type 'Type'.

I've tried various things such as

but the exception is always the same.

Can someone point me in the right direction?


Solution

  • Use something like this:

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

    The use of SubclassTypeValidator is not absolutely necessary, but most of the times you would use it ... I do at least.