- 打卡等级:即来则安
- 打卡总天数:29
- 打卡月天数:1
- 打卡总奖励:7791
- 最近打卡:2025-12-13 17:25:16
管理员
- 积分
- 21304
|
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);
- }
- }
- }
复制代码 来源:C#社区
网址:www.hicsharp.com
|
|