Welcome 微信登录

首页 / 网页编程 / ASP.NET / ASP.Net两种全局变量设置和读取

ASP.Net两种全局变量设置和读取2008-04-22本文介绍两种ASP.Net项目中全局变量使用的方式。web.config文件 和 Gloab文件。以下分别说明:

方法一:web.config文件

——设置:

在web.config文件里添加关键字key是通过<appSettings>标记来实现的,但是appSettings标记通常放在<system.web>.....</system.web>标记外面。例:

<configration>
<appSettings>
<add key="connString1" value="server=localhost;user id=sa;pwd=;database=数据库名字"/>
<add key="connString2" value="provider=Microsoft.Jet.OleDb.4.0;Data Source=数据库路径"/>
</appSettings>
<system.web>
</system.web>
</configration>

——读取:

要在代码中引用这些数据库连接字符串,需要先添加对System.ConFiguration名字空间的引用,在这个名字空间中含有ConfigurationSettings类,其静态方法ConfigurationSettings.AppSettings属性可获取web.config文件中节的设置,读到的值为string型。例如:

using System.Configuration;
string conn1 = ConfigurationSettings.AppSettings["connString1"];
string conn2 = ConfigurationSettings.AppSettings["connString2"];
SQLConnection myConn1 = new SQLConnection(conn1);
OleDbConnection myConn2 = new OleDbConnection(conn2);
在VS2005中, ConfigurationSettings.AppSettings 可以换成 ConfigurationManager.AppSettings

方法二:Gloab文件

——设置:

在Global文件里中添加

protected void Session_Start(Object sender, EventArgs e)
{
Session["sqlConnectionString"] = "uid=Username;pwd=password;database=MyTest;server=Localhost;Connect Timeout=300";
}

——读取:

在代码中的应用:

String strConnection=Session["sqlConnectionString"].ToString();
sqlConnection_1=new SqlConnection(strConnection);

推荐使用第一种方式!比较灵活,哈哈哈