Sunday, September 5, 2010

Create and use a custom configuration section in web.config

If you want to have a custom configuration section like the one defined below, you will have to define a class to handle it. The class needs to derive from ConfigurationSection.

<mySettings myval1="customvalue1" myval2="customvalue2" myval3="customvalue3"/>

Also you will have to define its structure in the configSections of the web.config:

<configuration>
      <configSections>
            <section name="mySettings" type="myNameSpace.mySettings"/>
      </configSections>
...
</configuration>


Note that the configSections, if defined, has to be the first child element of configuration element in the web.config file. The class can be defined this way:

public class mySettings: System.Configuration.ConfigurationSection
{
      [ConfigurationProperty("myval1", IsRequired=true)]
      public string myval1
      {
            get{return this["myval1"].ToString();}
            set{this["myval1"] = value;}
      }


      [ConfigurationProperty("myval2", IsRequired = true)]
      public string myval2
      {
            get{return this["myval2"].ToString();}
            set{this["myval2"] = value;}
      }

      [ConfigurationProperty("myval3", IsRequired = true)]
      public string myval3
      {
            get{return this["myval3"].ToString();}
            set{this["myval3"] = value;}
      }
}

No comments:

Post a Comment