1、添加Cookie
protected void Button1_Click(objectsender, EventArgs e)
{
HttpCookiecookies = new HttpCookie("website");
//方法一
cookies.Values.Add("name","Jianjie1");
cookies.Values.Add("sex","1");
//方法二
cookies["name"]= "Jianjie2";
cookies["sex"]= "0";
cookies.Expires = DateTime.Now.AddMinutes(60);
Response.Cookies.Add(cookies);
}
2、修改Cookie
新建一个页面CookieModify.aspx,进行测试
下面写法错误:
protected void Button1_Click(objectsender, EventArgs e)
{
HttpCookiecookies = Request.Cookies["website"];
if(cookies != null)
{
cookies.Values["name"] = this.TextBox1.Text;
cookies.Values.Add("newid", "0001");
}
}
再加上一句Response.AppendCookie(cookies);如下
protected void Button1_Click(objectsender, EventArgs e)
{
HttpCookiecookies = Request.Cookies["website"];
if(cookies != null)
{
cookies.Values["name"] = this.TextBox1.Text;
cookies.Values.Add("newid", "0001");
Response.AppendCookie(cookies);
}
}
再新建一个取值页面CookieGet.aspx,用它展示Cookie值,结果竟然报错
Cookies的值为NULL。
反复测试,发现在当前页面上跳转,Cookie取值正常,再打开一个新窗体页面中取值Cookie为NULL,
检查很久,最后尝试在修改页面CookieModify.aspx中增加过期时间:cookies.Expires =DateTime.Now.AddMinutes(60); 修改成功!
代码如下
protected void Button1_Click(objectsender, EventArgs e)
{
HttpCookiecookies = Request.Cookies["website"];
if(cookies != null)
{
cookies.Values["name"] = this.TextBox1.Text;
cookies.Values.Add("newid", "0001");
cookies.Expires = DateTime.Now.AddMinutes(60);
Response.AppendCookie(cookies);
}
}
自己理解:修改Cookie后Response.AppendCookie(cookies); Cookie的默认过期时间是当前会话有效,所以在当前页面中跳转可以正常取值,重新打开一个新的窗体Cookie过期了为空。所以最好还是给Expires赋予过期时间。
3、删除Cookie
删除Cookie中的一个Value键值
protected void btnDeleteItem_Click(objectsender, EventArgs e)
{
HttpCookiecookie = Request.Cookies["website"];
if(cookie != null)
{
cookie.Values.Remove("name");
cookie.Expires = DateTime.Now.AddMinutes(60);
Response.AppendCookie(cookie);
}
}
删除一个Cookie
protected void btnDeleteCookie_Click(objectsender, EventArgs e)
{
HttpCookiecookie = Request.Cookies["website"];
if(cookie != null)
{
cookie.Expires = DateTime.Now.AddDays(-1);
Response.AppendCookie(cookie);
}
}
以上代码均经过测试,删除成功!
本本原创来源于长沙软件公司