Cookie的使用

本文介绍ASP.NET中Cookies的基本操作及自定义对象存储方法。通过Request和Response对象直接操作Cookies,同时提供一个工具类实现对象形式的整体保存。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

(1)Asp.Net 中保存Cookies

通常,我们使用Request和Response对象来直接操作Cookies:

写入Cookies:

Response.Cookies["k1"].Value = "k1Value";
Response.Cookies["k2"]["k2-1"] = "k2-1Value";
Response.Cookies.Add(new HttpCookie("k3", "k3Value"));

读取Cookies:

Request["k1"] ;
Request.Cookies["k1"].Value ;
Request.Cookies["k2"]["k2-1"];
Request.Cookies.Get(0).Value;

注意Request["k1"]这个大家熟悉的获取get和post参数的方法,同时还能够获取Cookies的值!

另外上面语句中的有些是必须通过Value属性访问的,有些则不需要。

(2)以对象方式保存Cookies

下面提供一个可以以对象方式整体保存Cookies的工具类。并且只占用一条Cookies,所有的属性都存在子键上。

  • 源代码:  
    /// <summary>
    /// Cookies基类。将需要保存Cookies的数据类此类派生,可以将强类型对象在Cookies中的保存和读取。
    /// </summary>
    /// <remarks>
    /// 2009.8.6    ziqiu.zhang     created
    /// </remarks>
    /// <example>
    /// 假设MyCookiesInfo是从 从Cookies中获取对象:
    /// <code>
    ///     CookieInfo item = new CookieInfo(); //new以后已经从Cookies中构造了对象。
    /// </code>
    /// 将对象保存在Cookies中:
    /// <code>
    ///     CookieInfo item = new CookieInfo();
    ///     item.value = "test value";
    ///     item.SetCookies("1"); //Cookies有效期为1天
    /// </code>
    /// </example>
    [System.Serializable]
    public class CookieInfo
    {

        #region ==================== Constructed Method ====================
        /// <summary>
        /// 构造函数
        /// </summary>
        public CookieInfo()
        {

        }
        #endregion


        #region ==================== Public Method ====================
        /// <summary>
        /// 得到当前Cookies的过期时间
        /// </summary>
        /// <returns>过期时间</returns>
        public DateTime GetExpiresTime()
        {
            string cookieName = GetType().ToString();
            if (HttpContext.Current.Request.Cookies[cookieName] != null)
            {
                return HttpContext.Current.Request.Cookies[cookieName].Expires;
            }
            return DateTime.MinValue;
        }

        /// <summary>
        /// 保存Cookies,过期时间为浏览器关闭则失效。
        /// </summary>
        /// <param name="expiresTime">Cookies过期事件</param>
        /// <returns>是否保存成功</returns>
        public bool Save()
        {
            return this.Save(DateTime.MinValue);
        }

        /// <summary>
        /// 保存Cookies,需要指定过期时间。
        /// </summary>
        /// <param name="expiresTime">Cookies过期事件</param>
        /// <returns>是否保存成功</returns>
        public bool Save(DateTime expiresTime)
        {
            string CookieName = GetType().ToString();
            HttpCookie SessionCookie = null;

            //对 SessionId 进行备份.
            if (HttpContext.Current.Request.Cookies["ASP.NET_SessionId"] != null)
            {
                string SesssionId = HttpContext.Current.Request.Cookies["ASP.NET_SessionId"].Value.ToString();
                SessionCookie = new HttpCookie("ASP.NET_SessionId");
                SessionCookie.Value = SesssionId;

            }
            //设定cookie 过期时间.
            DateTime dtExpiry = expiresTime;
            HttpContext.Current.Response.Cookies[CookieName].Expires = dtExpiry;

            //设定cookie 域名.
            string domain = string.Empty;
            if (HttpContext.Current.Request.Params["HTTP_HOST"] != null)
            {
                //domain = "www.elong.com";
                domain = HttpContext.Current.Request.Params["HTTP_HOST"].ToString();
            }

            //如果是www.elong.com或多级域名,需要转化为elong.com
            if (domain.IndexOf(".") > -1)
            {
                string[] temp = domain.Split('.');

                if (temp.Length >= 3)
                {
                    domain = temp[temp.Length - 2].Trim() + "." + temp[temp.Length - 1].Trim();
                }

                HttpContext.Current.Response.Cookies[CookieName].Domain = domain;
            }


            //把类的属性, 写入Cookie.
            PropertyInfo[] Propertys = GetType().GetProperties();

            foreach (PropertyInfo pi in Propertys)
            {
                object oj = pi.GetValue(this, null);
                Type type = pi.PropertyType;
                string valueStr = string.Empty;

                if (oj != null && oj.ToString() != string.Empty)
                {
                    if (type == Type.GetType("System.DateTime"))
                    {
                        valueStr = ((DateTime)oj).ToString("yyyy/MM/dd HH:mm:ss", System.Globalization.DateTimeFormatInfo.InvariantInfo);
                    }
                    else
                    {
                        valueStr = oj.ToString();
                    }

                    HttpContext.Current.Response.Cookies[CookieName][pi.Name] = HttpUtility.UrlEncode(valueStr);
                }

            }

            //如果cookie总数超过20 个, 重写ASP.NET_SessionId, 以防Session 丢失.
            if (HttpContext.Current.Request.Cookies.Count > 20 && SessionCookie != null)
            {
                if (SessionCookie.Value != string.Empty)
                {
                    HttpContext.Current.Response.Cookies.Remove("ASP.NET_SessionId");
                    HttpContext.Current.Response.Cookies.Add(SessionCookie);
                }
            }

            return true;
        }

        /// <summary>
        /// 找回Cookie值
        /// </summary>
        public void Load()
        {
            string cookieValue = string.Empty;
            string CookieName = GetType().ToString();

            //通过遍历属性, 从cookie 中找回值, 回写到属性.
            PropertyInfo[] Propertys = GetType().GetProperties();

            foreach (PropertyInfo pi in Propertys)
            {
                try
                {
                    cookieValue = HttpUtility.UrlDecode(HttpContext.Current.Request.Cookies[CookieName][pi.Name].ToString());
                }
                catch
                {
                    cookieValue = string.Empty;
                }

                if (pi.CanWrite && cookieValue != null && cookieValue != string.Empty)
                {
                    try
                    {
                        object obb = cookieValue;
                        Type type = pi.PropertyType;

                        obb = Convert.ChangeType(obb, type);
                        pi.SetValue(this, obb, null);
                    }
                    catch { }

                }
            }

        }
        #endregion

    }
  • 使用

首先说明如何使用此类。

为想要保存在Cookies中的类建立模型,并且继承自CookieInfo即可。比如下面建立了MyCookieInfo类,其中包含属性pkid,TestValue和TestDateTime:

 

    /// <summary>
    /// 保存Cookies的数据对象
    /// </summary>
    [System.Serializable]
    public class MyCookieInfo : CookieInfo
    {    
        private int m_Pkid = 0; 
        public int Pkid
        {
            get
            {
                return m_Pkid ;
            }
            set
            {
                m_Pkid = value ;
            }
        }

        private string m_TestValue = "";
        public string TestValue
        {
            get
            {
                return m_TestValue;
            }
            set
            {
                m_TestValue = value;
            }
        }

        private DateTime m_TestDateTime = DateTime.Now;
        public DateTime TestDateTime
        {
            get
            {
                return m_TestDateTime;
            }
            set
            {
                m_TestDateTime = value;
            }
        }
    }

 

接下来就可以使用对象的Save和Load方法保存和读取Cookies:

  • 保存 
    Save方法有两个重载,不带参数的Save方法表示Cookies的过期时间与浏览器相同,即浏览器关闭则Cookies消失。否则需要传入Cookies过期时间。

    MyCookieInfo testCookies = new MyCookieInfo();
    testCookies.Pkid = 1;
    testCookies.TestValue = "中文测试";
    testCookies.Save(); 
  • 读取 
    MyCookieInfo testCookies = new MyCookieInfo();
    testCookies.Load();
    this.lblMsg.Text = "Pkid:" + testCookies.Pkid.ToString();
    this.lblMsg.Text += ",TestValue:" + testCookies.TestValue.ToString();
    this.lblMsg.Text += ",TestDateTime:" + 
    testCookies.TestDateTime.ToString("yyyy/MM/dd HH:mm:ss",
    System.Globalization.DateTimeFormatInfo.InvariantInfo);

现在我们已经可以将一个强类型的对象读取和保存Cookies了。

接下来就可以使用对象的Save和Load方法保存和读取Cookies:

  • 保存 
    Save方法有两个重载,不带参数的Save方法表示Cookies的过期时间与浏览器相同,即浏览器关闭则Cookies消失。否则需要传入Cookies过期时间。

    MyCookieInfo testCookies = new MyCookieInfo();
    testCookies.Pkid = 1;
    testCookies.TestValue = "中文测试";
    testCookies.Save(); 
  • 读取 
    MyCookieInfo testCookies = new MyCookieInfo();
    testCookies.Load();
    this.lblMsg.Text = "Pkid:" + testCookies.Pkid.ToString();
    this.lblMsg.Text += ",TestValue:" + testCookies.TestValue.ToString();
    this.lblMsg.Text += ",TestDateTime:" + 
    testCookies.TestDateTime.ToString("yyyy/MM/dd HH:mm:ss",
    System.Globalization.DateTimeFormatInfo.InvariantInfo);

现在我们已经可以将一个强类型的对象读取和保存Cookies了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值