当前位置: 首页 > 图文教程 > 网络编程 > ASP.NET > ASP.Net全局变量的设置和读取方法

ASP.NET
细细品味ASP.NET(一)
细细品味ASP.NET(二)
细细品味ASP.NET(三)
细细品味ASP.NET(四)
细细品味ASP.NET(五)
用asp.net和xml做的新闻更新系统(1)
用asp.net和xml做的新闻更新系统(2)
用asp.net和xml做的新闻更新系统(3)
十天学会ASP.net(1)
十天学会ASP.net(2)
十天学会ASP.net(3)
十天学会ASP.net(4)
十天学会ASP.net(5)
十天学会ASP.net(6)
十天学会ASP.net(7)
十天学会ASP.net(8)
十天学会ASP.net(9)
十天学会ASP.net(10)
ASP.NET创建XML Web服务全接触(1)
ASP.NET创建XML Web服务全接触(2)

ASP.NET 中的 ASP.Net全局变量的设置和读取方法


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-13   浏览: 145 ::
收藏到网摘: n/a

本文介绍两种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文件中<appSettings>节的设置,读到的值为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);
推荐使用第一种方式!比较灵活