ASP.NET Cookie 操作, 以用户登录退出为例, 实现Cookie的获取, 设置, 清除

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# 使用 CSVHelper 操作 csv 文件, .net core, .net framework 读取写入 csv 文件
C# 实现字符串文本换行的方法,文本如何换行
C# 如何循环读取文件每一行文本内容
C# DateTime AddMonths 的错误用法导致跳过日期
C# 全角转换半角,半角转换为全角