Skip to main content

Using NameValueSectionHandler to create custom configuration section in web.config

If you want to create custom section in web.config similar to appSettings section, you can use .NET build-in class NameValueSectionHandler.

1. Under web.config configSections element, add a new section config:


2. Create a section called "EncryptionSettings", outside the configSections element.

You can add as many key/value pairs as you want in this section.

3. In your application, get the section configuration using this code:
            NameValueCollection encConfig = ConfigurationManager.GetSection("EncryptionSettings") as NameValueCollection;
The return type of ConfigurationManager.GetSection() is actually ReadOnlyNameValueCollection. However, ReadOnlyNameValueCollection is an internal class to the System.dll assembly. So you can't refer to it from your code. It derives from System.Collections.Specialized.NameValueCollection, though, You can cast it into NameValueCollection. You are not able to change the collection since it is actually ReadOnlyNameValueCollection.
You can reference the configured key/value pairs using encConfig["MasterSecret"], etc.


Comments