我刚学asp.net,请问如何使用Cookie实现某一个用户登录后显示上次访问时间以及访问次数?麻烦写下关键代码,谢谢

解决方案 »

  1.   

       protected void Button1_Click(object sender, EventArgs e)
        {
            Response.Cookies["LastTime"].Value = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
            Response.Cookies["LastTime"].Expires = DateTime.Now.AddDays(60);
            int intTotTimes = 0;
            if (Request.Cookies["TotTimes"] != null)
            {
                intTotTimes = Convert.ToInt16(Request.Cookies["TotTimes"].Value); ;
            }
            intTotTimes = intTotTimes + 1;
            Response.Cookies["TotTimes"].Value = intTotTimes.ToString();
            Response.Cookies["TotTimes"].Expires = DateTime.Now.AddDays(60);    }
        protected void Button2_Click(object sender, EventArgs e)
        {
            if (Request.Cookies["LastTime"] != null)
            {
                this.TextBox1.Text = Request.Cookies["LastTime"].Value;
            }
            if (Request.Cookies["TotTimes"] != null)
            {
                this.TextBox2.Text = Request.Cookies["TotTimes"].Value;
            }    }
      

  2.   

    给你发一个通用的方法。
      /// <summary>
            /// 写cookie值
            /// </summary>
            /// <param name="strName">名称</param>
            /// <param name="strValue">值</param>
            public static void WriteCookie(string strName, string strValue)
            {
                HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
                if (cookie == null)
                {
                    cookie = new HttpCookie(strName);
                }
                cookie.Value = strValue;
                HttpContext.Current.Response.AppendCookie(cookie);        }        /// <summary>
            /// 写cookie值
            /// </summary>
            /// <param name="strName">名称</param>
            /// <param name="strValue">值</param>
            /// <param name="expires">过期时间(分钟)</param>
            public static void WriteCookie(string strName, string strValue, int expires)
            {
                HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
                if (cookie == null)
                {
                    cookie = new HttpCookie(strName);
                }
                cookie.Value = strValue;
                cookie.Expires = DateTime.Now.AddMinutes(expires);
                HttpContext.Current.Response.AppendCookie(cookie);        }        /// <summary>
            /// 读cookie值
            /// </summary>
            /// <param name="strName">名称</param>
            /// <returns>cookie值</returns>
            public static string GetCookie(string strName)
            {
                if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)
                {
                    return HttpContext.Current.Request.Cookies[strName].Value.ToString();
                }            return "";
            }