9.6. Adding Your Own Configuration Elements to web.config

Problem

You want to create and add your own configuration elements to web.config. No predefined element will do, nor will use of the <appSettings> key/value entries of web.config, as described in Recipe 9.2.

Solution

Determine what configuration information you want to store in web.config, create your own custom section handler for parsing the element, add the definition of the section handler to web.config, add the new configuration element to web.config, and then use the configuration information in your application.

  1. Determine what configuration information you want to store in web.config.

  2. Use the .NET language of your choice to create a custom section handler class for parsing your newly defined element.

  3. Add the definition of the section handler to the <configSections> section of web.config.

  4. Add the new configuration element to web.config and assign values to its attributes or child elements.

  5. In the code-behind class for your ASP.NET page, use the .NET language of your choice to access and put the custom configuration data to work.

The code we’ve written to illustrate this solution appears in Example 9-9 through Example 9-14. Example 9-9 (VB) and Example 9-10 (C#) show the class for a custom section handler. The changes we’ve made to web.config to have it use the custom section handler are shown in Example 9-11. Example 9-12 shows the .aspx file for a sample web form that displays some custom configuration settings. Example 9-13 ...

Get ASP.NET Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.