Add Custom Application Settings to web.config

ASP.NET provides for adding and then accessing configuration info specific to your app to the web.config file by using the <appSettings> element. Application configuration information is added by adding an child element to each parameter. Set the key attribute to the configuration parameter name, and then set the value attribute to the configuration parameter value:

 <appSettings> 
<add key="allowDataAccess" value="1" />
<add key="defaultDataOrder" value="Ascending" />
</appSettings>

When the ASP.NET app is started, ASP.NET creates a NameValueCollection from the key/value pairs in the  <appSettings> section. You can access the NameValueCollection anywhere in your app by using  the ConfigurationSettings object. Any data which can be represented as a string can be stored in the <appSettings> section, but note that data type other than a string will first need to be cast to from a string to that data type before being used  your app, for this reason your code should also incorporate exception handling for invalid data casts when the data is being accessed.

The below code demonstrates how to access the allowDataAccess configuration setting for the app. This is a boolean type (which is saved as a string):

Try

Dim allowDataBool as Boolean = ConfigurationSettings.AppSettings("allowDataAccess")

  If  allowDataBool Then
  '//Perform Data Access tasks
  End If

Catch ex As Exception

'//Perform error handling in the event that the allowDataAccess setting cannot be cast to a Boolean

End Try

Note that these settings are application wide and should not be used to set user specific settings, for this task consider either the Profile setting of ASP.NET Membership (for persistent information storage) or the Session object to store temporary information. Also be aware that changing the configuration settings in the web.config file will cause a restart of the application which will log out any current users.

Related Posts:

  • No Related Posts
Twitter Digg Delicious Stumbleupon Technorati Facebook Email

No comments yet... Be the first to leave a reply!