ASP.NET 中,在使用 Session 之前,我们强烈推荐您阅读 放飞技术网 的 ASP.NET Session 详解 一文(该文建立在 .NET Framework 1.0 的基础上),该文详细介绍了 ASP.NET 中 Session 的原理、配置方法以及相对 ASP 的突破点。
在 ASP.NET 中使用 Session 和 ASP 大致相同,注意的是:
- Session 是 Page 的一个属性,不是方法,所以在 C# 中,应该是使用中括号而不是小括号,比如是 Session["foo"] 而不是 Session("foo"),注意第一个 S 大写。
- 获取 Session 时,由于其是个 object,所以一般应该加 ToString() 将其转换成 string 类型。
示例
<%@ Page Language="C#" %>
<script runat="server">
void Page_Load()
{
Session["foo"] = "foo";
lb.Text = Session["foo"].ToString();
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>ASP.NET 中使用 Session</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lb" runat="server"></asp:Label>
</div>
</form>
</body>
</html>