//添加Cookie
protected void Button2_Click(object sender, EventArgs e)
{
HttpCookie cookie1 = new HttpCookie("MyCookie"); //初使化并设置Cookie的名称
//string Encryp1 = page.EncryptCookie(userName); //用户名加密
//string Encryp2 = page.EncryptCookie(userPwd); //密码加密
cookie1.Values.Add("loginName", Encryp1);//添加用户名
cookie1.Values.Add("loginPwd", Encryp2);//添加密码
Response.Cookies.Add(cookie1); //添加新建的cookie
}
//修改Cookie
protected void Button3_Click(object sender, EventArgs e)
{
//获取客户端的Cookie对象
HttpCookie cok = Request.Cookies["MyCook"];
if (cok != null)
{
//修改Cookie的两种方法
cok.Values["userid"] = "alter-value";
cok.Values.Set("userid", "alter-value");
//往Cookie里加入新的内容
cok.Values.Set("newid", "newValue");
Response.AppendCookie(cok);
}
}
//************************************************
//以下未进行验证
//删除Cookie
protected void Button4_Click(object sender, EventArgs e)
{
HttpCookie cok = Request.Cookies["MyCook"];
if (cok != null)
{
if (!CheckBox1.Checked)
{
cok.Values.Remove("userid");//移除键值为userid的值
}
else
{
TimeSpan ts = new TimeSpan(-1, 0, 0, 0);
cok.Expires = DateTime.Now.Add(ts);//删除整个Cookie,只要把过期时间设置为现在
}
Response.AppendCookie(cok);
}
}
部分来源于:http://blog.163.com/kele_lipeng/blog/static/81345278201082993211735/