Programmatically Read Web.config Settings

To read the values that are configured in an ASP.NET Web.config file you will need to create objects for different sections of the Web.config file.

For example: To read the Web.config settings that are in the system.web/authentication/forms section, check out the code snippet below:

<configuration>
 <system.web>
  <authentication>
   <forms>
    <!-- The example below shows how you can read the settings within this forms element -->
   </forms>
  </authentication>
 </system.web>
</configuration>
// Get the Web application configuration.
System.Configuration.Configuration configuration =
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/");

// Get the external Authentication section.
System.Web.Configuration.AuthenticationSection authenticationSection =
(System.Web.Configuration.AuthenticationSection)configuration.GetSection(
"system.web/authentication");

// Get the external Forms section .
System.Web.Configuration.FormsAuthenticationConfiguration formsAuthentication =
authenticationSection.Forms;

System.Diagnostics.Debug.WriteLine(string.Format("DefaultUrl: {0}.", formsAuthentication.DefaultUrl));
System.Diagnostics.Debug.WriteLine(string.Format("Domain: {0}.", formsAuthentication.Domain));
System.Diagnostics.Debug.WriteLine(string.Format("EnableCrossAppRedirects: {0}.", formsAuthentication.EnableCrossAppRedirects));
System.Diagnostics.Debug.WriteLine(string.Format("LoginUrl: {0}.", formsAuthentication.LoginUrl));
System.Diagnostics.Debug.WriteLine(string.Format("Name: {0}.", formsAuthentication.Name));
System.Diagnostics.Debug.WriteLine(string.Format("Path: {0}.", formsAuthentication.Path));
System.Diagnostics.Debug.WriteLine(string.Format("Protection: {0}.", formsAuthentication.Protection));
System.Diagnostics.Debug.WriteLine(string.Format("RequireSSL: {0}.", formsAuthentication.RequireSSL));
System.Diagnostics.Debug.WriteLine(string.Format("SlidingExpiration: {0}.", formsAuthentication.SlidingExpiration));
System.Diagnostics.Debug.WriteLine(string.Format("Timeout: {0}.", formsAuthentication.Timeout));
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s