(转)用cookie保存浏览记录 (转载:http://blog.csdn.net/keyake863/archive/2008/03/31/2233404.a
时间:2011-02-17 来源:吐气的泡泡
当页面初始化时需要判断是否存在
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Cookies["username"] == null)
{
HttpCookie myCookie = new HttpCookie("username");
myCookie.Values.Add("prodid", "");
myCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(myCookie);
}
}
这是插入cookie的代码
public void addcookie(string cookievalue)
{
HttpCookie cookie = new HttpCookie("username");
if (Request.Cookies["username"].Values["prodid"] != "")
{
string myvalue = "";
myvalue = Request.Cookies["username"].Values["prodid"].ToString();
myvalue = cookievalue + "," + myvalue;
cookie.Values.Add("prodid", myvalue);
cookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(cookie);
}
else
{
cookie.Values.Add("prodid", cookievalue);
cookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(cookie);
}
}
读取cookie代码,只读取最后三条记录
public void playcookie()
{
int num = 0;
string myvalue = "";
myvalue = Request.Cookies["username"].Values["prodid"].ToString();
string resultvalue=string.Empty;
if (myvalue != "")
{
Char[] spitchar = new Char[] ...{ Convert.ToChar(",") };
string[] cookievalue;
cookievalue = myvalue.Split(spitchar);
if (cookievalue.Length <= 3)
{
num = cookievalue.Length;
}
else
{
num = 3;
}
for (int i = 0; i < num; i++)
{
resultvalue += cookievalue[i].ToString();
}
Label1.Text = resultvalue;
}
}
最后是删除cookie的方法
protected void Button2_Click(object sender, EventArgs e)
{
HttpCookie myCookie = new HttpCookie("username");
myCookie.Expires = DateTime.Now.AddDays(-1d);
Response.Cookies.Add(myCookie);
}
本文完,代码不多,也许测试用例未做过多测试,就当抛砖引玉,本文有科雅客原创,未经许可切勿转载
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/keyake863/archive/2008/03/31/2233404.aspx