Programming Microsoft ASP.NET 4 - Dino Esposito [61]
Retrieving Application Settings
public static NameValueCollection AppSettings { get {return ConfigurationManager.AppSettings;} } public static NameValueCollection ConnectionStrings { get {return ConfigurationManager.ConnectionStrings;} } As you can see, to access application settings and connection strings you can interchangeably use the AppSettings and ConnectionStrings collections on both WebConfigurationManager and ConfigurationManager. Here’s how to obtain a registered connection string named Northwind: WebConfigurationManager.ConnectionStrings["Northwind"].ConnectionString For a value stored in the WebConfigurationManager.AppSettings["CacheDurationForData"] In case you need to access other sections outside var name = @"system.net/webRequestModules"; Configuration cfg = ConfigurationManager.OpenMachineConfiguration(); var section = (WebRequestModulesSection) cfg.GetSection(name); foreach (WebRequestModuleElement m in section.WebRequestModules) { ... } To explore the content of a section, you need to cast the return value of the GetSection method to a specific type. A section type is defined for each system-provided supported section in the system.configuration assembly. Note, though, that you won’t find any such section classes for elements under the Updating Application Settings var name = @"system.web/httpHandlers"; var path = "/myapp"; var config = WebConfigurationManager.OpenWebConfiguration(path); var section = (HttpHandlersSection) config.GetSection(name); var newHandler = new HttpHandlerAction("*.xyz", "System.Web.HttpForbiddenHandler", "*"); section.Handlers.Add(newHandler); config.Save(); The newly added handler configures the system so that requests for .xyz files are blocked. The application’s web.config file is modified as follows: ... type="System.Web.HttpForbiddenHandler" /> To re-enable .xyz resources, you need to remove the handler that was just added. The following code shows how to proceed programmatically: var name = @"system.web/httpHandlers"; var path = "/myapp"; var config = WebConfigurationManager.OpenWebConfiguration(path); var section = (HttpHandlersSection) config.GetSection(name); section.Handlers.Remove("*", "*.xyz"); config.Save(); After this, any request for an .xyz resource is likely to produce the, perhaps more familiar, “resource not found” message. Encrypting a Section
As mentioned, most ASP.NET applications need to access data in sections outside the
The entire content of the configuration tree is exposed to applications through a sort of Document Object Model (DOM). This DOM is modifiable in memory. After you’re done, you can persist changes by calling the Save method on the corresponding Configuration class. The following code snippet shows how to programmatically add a new HTTP handler to the current application: