A simple example of how the web.config file custom configuration section is used
The program used to demonstrate myApp, namespace is also myapp
1. Edit Web.config file
Add the following, declare a section
configsections>
Declare a section called Appconfig
2. Edit Web.config file
Add the following, join a section
Appconfig>
This section includes two keys
3. Dead from IconfigurationSectionHandler, Appconfig
Implement the CREATE method, the code is as follows
public class AppConfig: IConfigurationSectionHandler {static String m_connectionString = String.Empty; static Int32 m_userCount = 0; public static String ConnectionString {get {return m_connectionString;}} public static Int32 UserCount {get {return m_userCount;}}
Static String Readsetting (NameValueCollection NVC, String Key, String DefaultValue) {string thevalue = NVC [key]; if (thevalue == string.empty) Return DefaultValue;
Return thevalue;}
public object Create (object parent, object configContext, XmlNode section) {NameValueCollection settings; try {NameValueSectionHandler baseHandler = new NameValueSectionHandler (); settings = (NameValueCollection) baseHandler.Create (parent, configContext, section);} catch {settings = null; } if (settings = null!) {m_connectionString = AppConfig.ReadSetting (settings, "ConnectionString", String.Empty); m_userCount = Convert.ToInt32 (AppConfig.ReadSetting (settings, "UserCount", "0"));} return Settings;}} We map all the configurations into the corresponding static member variables and write to read-only properties so that the program passes
Similar to appconfig.connectionstring can access, the project in the configuration file is
4. Finally, I have to do something.
Add the following code to Application_Start in Global.asax.cs
System.configuration.configurationSettings.getConfig ("Appconfig");
In this way, after the program is started, the value in the section of AppConfig will be read, and the system will call your own IconfigurationSectionHandler interface to read the configuration.