Extending web.config with your custom configuration sections – level 300

The web.config file in ASP.NET enables configuration of the entire ASP.NET application.  It is a file that is part of just about every ASP.NET application, yet I see many developer who roll their own configuration schemes beside the web.config file instead of making use of the functionality already built in.  Yes, some may use the appSettings section and then just retrieve a value from a key, but web.config can do so much more than that!  Here is a sample of how easy it is to add your own configuration section, thereby partitioning a section of configuration items away from the others:



<sectionGroup name=”MyCompany.MyApp.MyNamespace”>

<section name=”SomeClassesConfig”

type=“MyCompany.MyApp.MyConfigHandler“,MyCompany.MyApp” />





<add key=”myKey” value=”myValue” />




Then, in your code, you just have a class, MyCompany.MyApp.MyConfigHandler that inherits from System.Configuration.NameValueSectionHandler, and that’s all it takes.  If you don’t make your own ConfigHandler, then you have to specify the strong name in your type=”” attribute, and not only is that painful, but when you migrate this code to .Net 2.0 and beyond, you will have to modify every place where you gave a strong name.  If you make a superclass of it, then when you migrate the superclass, you’re golden.

To get to these values in your code, you just use a NameValueCollection that you can get from calling:


Does that look like an XPath expression to you?

You can further extend the web.config file with your own ConfigHandler that has nested XML elements instead of just a key and a value.  You could store complete object information in the web.config (if the data rarely changes).  Remember that every change of the web.config forces a restart on that directory and its children.

Coming up in May of next year, .Net 2.0 will have the APIs to modify .config files programmatically.  Check out the Beta 1 to use this functionality right now.