Session对象
Session对象记录浏览器端的变量对象,用来存储跨网页程序的变量或对象。
服务器会为连接的客户端分配各自的Session对象 ,不同的客户端无法互相存取,当超过设置的有效时间时候Session对象会消失。
Session是Page对象的成员可以直接在网页中使用。使用Session对象存放信息的语法:
Session[“变量名”]=“内容”;
从绘画中读取信息的语法:
VariablesName=Session["变量名"];
Contents属性 用于获取对当前会话状态对象的引用
public HttpSessionState Contents {get;}
实例,当程序运行时候,通过调用Session对象的Contents属性获取对象集合,然后循环输出Session变量的值。
protected void Page_Load(object sender, EventArgs e) { //Session对象赋值 Session["id1"] = "ID1"; Session["id2"] = "ID2"; Session["id3"] = "ID3"; foreach (string str in Session.Contents) { Response.Write(Session[str].ToString()); Response.Write("</br>"); } }
TimeOut属性 获取并设置会话状态提供程序终止会话之前个请求之间所允许的时间(以分钟为单位)。
public intTineout {get;set;} 超时时限。默认20分钟。早web.config、文件中使用sessionState配置元素的timeout属性来设置TimeOut。也可以直接设置,不能设525600分钟(1年)。
<sessionState mode="InProc" timeout="30"/>
-------------------------------------------------------------------------------------------Session常用方法
Session.Clear()
Session.Add(string name,object value);
Login.aspx页面
<body> <form id="form1" runat="server"> <div> 用户名:<asp:TextBox ID="txtName" runat="server"></asp:TextBox> <br /> <br /> <br /> 密码: <asp:TextBox ID="txtPwd" runat="server" TextMode="Password"></asp:TextBox> <br /> <br /> <asp:Button ID="btnLogin" runat="server" Text="登录" onclick="btnLogin_Click" /> <asp:Button ID="btnCancel" runat="server" Text="取消" /> <br /> <br /> </div> </form> </body>
后台代码:
protected void btnLogin_Click(object sender, EventArgs e) { if (txtName.Text == "mr" && txtPwd.Text == "mr") { Session["UserName"] = txtName.Text; Session["TimeLogin"] = DateTime.Now; Response.Redirect("~/UserPage.aspx"); } else { Response.Write("<script> alert('登录失败');Location='Login.aspx'</script>"); } }
UserPage.aspx代码:
protected void Page_Load(object sender, EventArgs e) { Response.Write("欢迎用户"+Session["UserName"].ToString()); Response.Write("您登陆的时间为" + Session["TimeLogin"].ToString()); }