12.5. Accessing Other web.config Configuration Elements

Problem

You want to be able to read application information from a web.config file that is unavailable as an <appSettings> key/value pair but present as an attribute or child element of some other element of the file.

Solution

Use the OpenWebConfiguration method of the WebConfigurationManager object to read the web.config file into a Configuration object, and use the GetSection method to access the desired section.

In the code-behind class for your ASP.NET page, use the .NET language of your choice to:

  1. Use the OpenWebConfiguration method of the WebConfigurationManager object to read the web.config file into a Configuration object.

  2. Use the GetSection method to access the desired section.

  3. Cast the returned ConfigurationSection object to the type of the object for the section being accessed.

  4. Use the properties of the object to access the desired information.

Examples 12-6, 12-7 through 12-8 show an application we’ve written that implements this solution and retrieves attribute settings from the <trace> element of a web.config file. Example 12-6 shows the .aspx file that displays the information. Examples 12-7 (VB) and 12-8 (C#) show the code-behind class for the page that does the work of reading the settings from the <trace> element.

Discussion

In ASP.NET 1.x, you had to resort to opening the web.config file using an XmlDocument object to access many of the configuration elements. In ASP.NET 2.0, new classes have been introduced to read ...

Get ASP.NET 2.0 Cookbook, 2nd Edition 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.