在Asp.net里,Session用来在服务器端为每个用户会话保存独立的数据,比如用户编号、昵称或购物车内容。它基于Cookie或URL标识来区分不同访问者,比ViewState更适合跨页面传递敏感信息。

Session的基本读写
在后台代码(如aspx.cs)中,可以直接通过Session属性进行赋值和取值。Session本质是一个键值集合,键通常为字符串。
// 写入Session
Session["UserName"] = "张三";
Session["UserId"] = 1001;
// 读取Session
string name = Session["UserName"] as string;
if (name != null)
{
// 输出欢迎信息
Response.Write("欢迎:" + name);
}
保存自定义对象
Session不仅能存基本类型,也可以存类实例,但该类最好标记可序列化,方便在进程外模式中使用。
public class UserInfo
{
public int Id { get; set; }
public string Name { get; set; }
}
// 存入对象
UserInfo user = new UserInfo { Id = 1, Name = "李四" };
Session["CurrentUser"] = user;
// 取出对象
UserInfo u = Session["CurrentUser"] as UserInfo;
设置超时时间
Session默认超时是20分钟,可在web.config里调整,避免用户停留稍久就被登出。
<configuration>
<system.web>
<sessionState timeout="30" mode="InProc" />
</system.web>
</configuration>
清除与销毁
退出登录时应释放Session,防止占用服务器资源。
- Session.Remove("UserName") 删除单个键
- Session.Clear() 清空所有键
- Session.Abandon() 结束当前会话
常见注意点
使用Session时要注意,若mode设为InProc,网站重启会导致数据丢失;高并发时可考虑StateServer或SQLServer模式。另外,在代码里写Session["key"]时,键名拼写错误不会报错,但读出来为null,需要做好判空。
Session是Asp.net状态管理的重要工具,合理使用能提升用户体验,但别往里面塞过大对象。
简单页面示例
<%@ Page Language="C#" %>
<script runat="server">
protected void btnSave_Click(object sender, EventArgs e)
{
Session["test"] = txtValue.Text;
lblMsg.Text = "已保存";
}
protected void btnRead_Click(object sender, EventArgs e)
{
lblMsg.Text = "值为:" + (Session["test"] as string);
}
</script>
<form id="form1" runat="server">
<asp:TextBox ID="txtValue" runat="server" />
<asp:Button ID="btnSave" runat="server" Text="保存" OnClick="btnSave_Click" />
<asp:Button ID="btnRead" runat="server" Text="读取" OnClick="btnRead_Click" />
<asp:Label ID="lblMsg" runat="server" />
</form>