Creating Custom Configuration Sections in ASP.NET

You are currently viewing Creating Custom Configuration Sections in ASP.NET

Almost all ASP.NET Web Applications require some sort of configuration settings to be stored in the web.config files. These settings can be application settings, database connection strings, user authentication settings, page specific settings and so on. ASP.NET also provides very powerful Configuration API to work with configuration settings defined in web.config files. The Configuration API not only allows us to read/write settings in configuration files with ease but also allow us to define our own custom configuration sections in web.config. These custom sections are very useful in large web applications where you have a lot of application settings to store in the configuration file. In this tutorial, I will show you how to create and use custom configuration sections in ASP.NET.

I am sure many of you are using the following appSettings section of web.config to define your application specific settings.

   <add key="DefaultLanguage" value="English-US"/>
   <add key="WebsiteTitle" value="Microsoft Corporation"/>   
   <add key="MaximumTransactionLimit" value="100000"/>

However, in large projects you end up having an endless list of key/value pairs in your web.config file. This makes life little difficult as you have to make sure when you are reading these values you are typing the spellings of all keys correctly e.g. DefautlLanguage is not same as DefaultLanguage. You also need to do lot of type casting when you are reading all types of values such as numbers, Booleans, dates, etc.

To solve these problems, ASP.NET allows us to create a custom configuration section in web.config. A custom configuration section can be defined in the element in web.config. You need to specify the name of the section and the class name that is responsible for serialization and de-serialization of attributes of custom configuration section into class properties. Following is an example of custom configuration section defined for a typical ecommerce web application.

      <section name="ShoppingCartSettings" type="ShoppingCartSection"/>

Please keep in mind that the value given for the type attribute above is the fully qualified name of the class. If the class is in App_Code folder of your project, you can simply use its name as used in the above example. If the class is in another assembly (.dll) then you need to use “Namespace.ClassName, AssemblyName” as the value of the type attribute. Once you have defined the custom configuration section you can use it in web.config file anywhere inside root configuration element as shown in the following code.



      paypalCheckoutEnabled="true" />


You can define any number of properties in the ShoppingCartSettings section but keep in mind that these properties need to be defined in the class named ShoppingCartSection as mentioned above in the type attribute. ShoppingCartSection class will be a simple C# class inherited from the System.Configuration.ConfigurationSection class. To define this class, add the reference of System.Configuration in your project and import the namespace on the top of the file with using statement.

using System.Configuration; 

public class ShoppingCartSection : ConfigurationSection 

The ShoppingCartSection class represents the root ShoppingCartSettings element of the custom configuration section defined in web.config file. Next you need to define the properties of the class as shown in the following code.

public class ShoppingCartSection : ConfigurationSection
   [ConfigurationProperty("defaultCurrency", IsRequired = true, DefaultValue="USD")]
   [StringValidator(MinLength=1, MaxLength=100)]
   public string DefaultCurrency
      get { return (string)this["defaultCurrency"]; }
      set { this["defaultCurrency"] = value; }

   [ConfigurationProperty("maxItemsInCart", IsRequired = true, DefaultValue = "5")]
   [IntegerValidator(MinValue=1, MaxValue=10)] 
   public int MaxItemsInCart
      get { return Convert.ToInt32(this["maxItemsInCart"]); }
      set { this["maxItemsInCart"] = value; }

   [ConfigurationProperty("paypalCheckoutEnabled", IsRequired = false, DefaultValue = false)]
   public bool PaypalCheckoutEnabled
      get { return Convert.ToBoolean(this["paypalCheckoutEnabled"]); }
      set { this["paypalCheckoutEnabled"] = value; }

Notice how the class properties MaxItemsInCartDefaultCurrency etc. are mapped with the attributes defined in custom configuration element in web.config using the ConfigurationProperty attribute declaration on top of the properties. The ConfigurationProperty attribute is also using some other parameters such as DefaultValue and IsRequired. The DefaultValue parameter specifies the default value of the property if it is not defined in the web.config. The IsRequired parameter specified whether the attribute defined in web.config is required or optional. I have also used the StringValidator and IntegerValidator attributes in the above code to show you how to validate the values specified in the web.config.

READ ALSO:  Saving images in database using ASP.NET FileUpload Control

To read the custom configuration section data in your web pages you can use the static GetSection method of ConfigurationManager class as shown below:

ShoppingCartSection settings = 
   ConfigurationManager.GetSection("ShoppingCartSettings") as ShoppingCartSection;

Label1.Text = "Default Currency: " + settings.DefaultCurrency;
Label2.Text = "Max Allowed Items in Shopping Cart: " + settings.MaxItemsInCart.ToString();
Label3.Text = "Paypal Checkout Enable: " + settings.PaypalCheckoutEnabled.ToString();

In this tutorial, I have shown you how you can use the .NET Configuration API to define custom configuration sections in web.config files. I have also shown you how to define read the values from custom section. I hope you have found this tutorial useful and learned something new to use in your projects.

This Post Has 3 Comments

  1. Ivan Đapić

    This article about config custom sections is among the best you can find currently.

  2. Sarmad Ali

    Thanks alot … Great Article easy to understand it helps me a lot thank again !!!

Leave a Reply