ASP.NET Session 操作, 以用户登录退出为例, 实现Session的获取, 设置, 清除
using System;
using System.Web;
namespace WebApplication4
{
/// <summary>
/// ASP.NET Session 操作, 以用户登录退出为例, 实现Session的获取, 设置, 清除
/// </summary>
public partial class Default : System.Web.UI.Page
{
/// <summary>
/// 载入, 获取Session
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(object sender, EventArgs e)
{
string user = "";
// 读取Session
if (HttpContext.Current.Session["User"] != null)
{
user= HttpContext.Current.Session["User"].ToString();
}
Response.Write("当前登录用户: " + user);
}
/// <summary>
/// 登录, 设置Session
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnLogin_Click(object sender, EventArgs e)
{
// 设置Session, 5分钟后过期
HttpContext.Current.Session["User"] = "Admin";
HttpContext.Current.Session.Timeout = 5;
// 再次刷新页面
HttpContext.Current.Response.Redirect("Default.aspx", false);
}
/// <summary>
/// 退出, 清除Session
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnLogOff_Click(object sender, EventArgs e)
{
// 清除Session
if (HttpContext.Current.Session != null)
{
HttpContext.Current.Session["User"] = null;
}
// 再次刷新页面
HttpContext.Current.Response.Redirect("Default.aspx", false);
}
}
}