Question

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

  • renaming the attribute to valueType (to avoid any clashes with a possible pre-configured attribute of the same name)
  • specifying it simply as "System.String"
  • changing the getter in the property to return (Type) this["type"];

but the exception is always the same.

Can someone point me in the right direction?

Was it helpful?

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top