As you no doubt already now it, the .NET Framework stores application configuration information in dedicated XML files, with the extension of .config. You can easily manage your application using these configuration files. When working with ASP.NET, the hierarchy is as follows:
- Machine web.config
- Root (application) web.config
- Subfolder web.config
These configuration files will be merged during runtime, and the application works with the merged content. Every setting defined in a higher level of the configuration hierarchy overrides its predecessors (but only if overriding them is enabled).
One of the most important settings provided here is the machine key. ASP.NET uses the machine key for several distinct encryption and validation operations, for example encrypting or validating the View State, or checking the validity of sessions. In a web farm environment, you should explicitly set the machine key (which can be set in the Machine.config file), because it isn’t guaranteed that the request will be posted back and handled by the same computer. This results in serious errors, since two computers with different machine keys can’t interpret and decrypt each other’s hashes, keys, etc.
One of the biggest benefit of .config files is that settings aren’t hard coded into the application itself, so you don’t have to rewrite the whole application (and during this, hunt for sections of your code in which settings are defined). Instead, mere humans can simply change the application behavior by simply manipulating a human-readable and understandable XML file. This benefit can be easily turn into a nightmare when you store secrets (like SQL server authentication information) or similar confidential data in these files. To protect yourself from potential attackers, its generally a good idea to encrypt .config sections. You can do so by using the aspnet_regiis command line tool, or programmatically, by calling the ProtectSection and UnprotectSection methods of the SectionInformation property.
There are cases when you need to define custom sections in your configuration files. To do so, you should take the following steps:
- Determine the information you need to store in a custom section, and how it can be structured into XML elements and attributes.
- Create a new class for each new element.
- Register the new section in your configuration file, by using the configSections section.