- 打卡等级:即来则安
- 打卡总天数:29
- 打卡月天数:1
- 打卡总奖励:7791
- 最近打卡:2025-12-13 17:25:16
管理员
- 积分
- 21304
|
ASP.NET Cookie 操作, 以用户登录退出为例, 实现Cookie的获取, 设置, 清除- using System;
- using System.Web;
-
- namespace WebApplication4
- {
- /// <summary>
- /// ASP.NET Cookie 操作, 以用户登录退出为例, 实现Cookie的获取, 设置, 清除
- /// </summary>
- public partial class Default : System.Web.UI.Page
- {
- /// <summary>
- /// 载入, 获取Cookie
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- protected void Page_Load(object sender, EventArgs e)
- {
- string user = "";
- // 读取Cookie
- HttpCookie cookie = HttpContext.Current.Request.Cookies["User"];
- if (cookie != null)
- {
- user = cookie.Value;
- }
- Response.Write("当前登录用户: " + user);
- }
-
- /// <summary>
- /// 登录, 设置Cookie
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- protected void btnLogin_Click(object sender, EventArgs e)
- {
- // 设置Cookie, 5分钟后过期
- HttpCookie cookie = new HttpCookie("User")
- {
- Value = "Admin",
- Expires = DateTime.Now.AddMinutes(+5)
- };
- HttpContext.Current.Response.Cookies.Add(cookie);
-
- // 如果未设置Cookie过期时间, 则Cookie的有效期只在当前页面, 关闭浏览器再次进入就无效了过期了
- //HttpCookie cookie = new HttpCookie("User")
- //{
- // Value = "Admin"
- //};
- //HttpContext.Current.Response.Cookies.Add(cookie);
-
- // 再次刷新页面
- HttpContext.Current.Response.Redirect("Default.aspx", false);
- }
-
- /// <summary>
- /// 退出, 清除Cookie
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- protected void btnLogOff_Click(object sender, EventArgs e)
- {
- // 清除Cookie
- HttpCookie cookie = HttpContext.Current.Request.Cookies["User"];
- if (cookie != null)
- {
- HttpContext.Current.Response.Cookies["User"].Expires = DateTime.Now.AddSeconds(-1);
- }
-
- // 再次刷新页面
- HttpContext.Current.Response.Redirect("Default.aspx", false);
- }
- }
- }
复制代码 来源:C#社区
网址:www.hicsharp.com
|
|