發布時間:2020-08-06 21:42 作者:獨孤劍 閱讀:3319
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); } } }
微信打賞, 微信掃一掃
支付寶打賞, 支付寶掃一掃
如果文章對您有幫助,歡迎給作者打賞