In Asp.Net we can store constants and global information in the web.config file, these details can be accessed from anywhere in the Asp.net application. Let us see how to save connection strings and other application level constants in the web.config file and how to retrieve them from the application.
Create a new Asp.Net site or Application, open the web.cong file and place the required details under the appSettings & connectionStrings sections.
<appSettings>
<add key="Environment" value="local" />
</appSettings>
<add key="Environment" value="local" />
</appSettings>
<connectionStrings>
<add name="ConnectionString" connectionString="xxxxxxxxx"/>
</connectionStrings>
Now let us see how this information can be accessed from the application.
Before staring add the below assembly reference to the top of the page, from where you are trying to read the details from the web.config file.
using System.Configuration;
string strConn =ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
string strEnvironment = ConfigurationManager.AppSettings["Environment"].ToString();
Once the above lines are executed the variable strConn will contain the value of the connection string, and the variable strEnvironment will contain the value local.
It is advisable to encrypt the connection string and place the same in the web.config, so that if an unauthorized person manages to access the web.config file, he will still not be able to interpret the server connection details.
No comments:
Post a Comment