Extending web.config in ASP.NET

Last March I wrote about how handy it is that ASP.NET enables you to add your own custom settings to the web.config file using syntax like this:

<appSettings>
<add key=”connString” value=”user id=sa;password=mypassword;” />
</appSettings>

This is nice, but can quickly get unwieldy if you have alot application settings to maintain. Back in March I failed to mentioned (because I didn’t know about it) that you can extend your web.config even further by creating your own custom configuration sections. You can read more about the ConfigurationSettingsSchema on msdn, but here’s a quick example. First you define the custom application settings:

<configSections>
   <sectionGroup name=”myapplication”>
      <section name=”types” type=”System.Configuration.NameValueSectionHandler”/>
      <section name=”security” type=”System.Configuration.NameValueSectionHandler”/>
    </sectionGroup>
</configSections>

and then you add the actual settings:

<myapplication>
   <types>
      <add key=”section” value=”com.ignitionlabs.Section” />
      <add key=”template” value=”com.ignitionlabs.Template” />
   </types>
   <security>
      <add key=”/controlpanel/” value=”Systems Administrators,Project Managers” />
      <add key=”/members/” value=”members” />   
   </security>
</myapplication>

Finally, you can use the exact same XPATH syntax that you use when retrieving other application settings. In the above example, there are multiple ‘type’ elements, so I’d first get a NameValueCollection object:

NameValueCollection config = (NameValueCollection)System.Configuration.ConfigurationSettings.GetConfig(“myapplication/types”);

and then retrieve the value of the “section” key using the name:

string section = config["section"];

Enjoy!

2 thoughts on “Extending web.config in ASP.NET”

  1. Great piece, I have been searching for a good example on for some time, and yours is spot on. I’m using .NET 2.0, so now it’s System.Configuration.ConfigurationManager.GetSection and not System.Configuration.ConfigurationSettings.GetConfig but other then that, no problem. Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>