This article introduces two ways to use global variables in ASP.Net projects. web.config file and Gloab file. The following are respectively explained:
Method 1: web.config file - settings:
Adding keyword keys in the web.config file is achieved through the <appSettings> tag, but the appSettings tag is usually placed outside the <system.web>.....</system.web> tag. example:
<configration>
<appSettings>
<add key="connString1" value="server=localhost;user id=sa;pwd=;database=database name"/>
<add key="connString2" value="provider=Microsoft.Jet.OleDb.4.0;Data Source=database path"/>
</appSettings>
<system.web>
</system.web>
</configration>
- Read:
To reference these database connection strings in code, you need to first add a reference to the System.ConFiguration namespace. This namespace contains the ConfigurationSettings class, and its static method ConfigurationSettings.AppSettings property can obtain the <appSettings> section in the web.config file. Setting, the value read is string type. For example:
using System.Configuration;
string conn1 = ConfigurationSettings.AppSettings["connString1"];
string conn2 = ConfigurationSettings.AppSettings["connString2"];
SQLConnection myConn1 = new SQLConnection(conn1);
OleDbConnection myConn2 = new OleDbConnection(conn2);
In VS2005, ConfigurationSettings.AppSettings can be replaced by ConfigurationManager.AppSettings
Method 2: Gloab file
--set up:
Add in Global file
protected void Session_Start(Object sender, EventArgs e)
{
Session["sqlConnectionString"] = "uid=Username;pwd=password;database=MyTest;server=Localhost;Connect Timeout=300";
}
——Read:
Application in code:
String strConnection=Session["sqlConnectionString"].ToString();
sqlConnection_1=new SqlConnection(strConnection);
It is recommended to use the first method! More flexible