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)
            {
                cookie.Value = "";
                cookie.Expires = DateTime.Now.AddSeconds(-1);
                HttpContext.Current.Response.Cookies.Add(cookie);
            }

            // 再次刷新页面
            HttpContext.Current.Response.Redirect("Default.aspx", false);
        }
    }
}

作者最新文章
Winform TextBox (文本框) 密码输入框, 输入内容显示*号 (星号)
Winform 启动前弹出登录界面, 登录成功之后再显示主界面
C# 字符串string和字符数组char[]的相互转换
C# 字符串倒序输出, 实现字符串倒序的方法
Winform 如何从 TextBox(文本框) 控件读取每一行数据到数组