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);
        }
    }
}

作者最新文章
ASP.NET aspx获取服务器信息, 操作系统, .NET版本, IIS版本
C# Unix转换本地时间, Unix时间戳转换DateTime
C# 获取Unix时间戳
C# DateTime.Ticks 转换为 DateTime
C# 数字转换字符串左边补0, 数字前补0的方法