asp.net 操作cookie实例详解

发布时间:2020-09-22编辑:脚本学堂
本文介绍了asp.net操作cookie的一个实例代码,学习下asp.net cookie操作的方法,有需要的朋友参考下。

例子,asp.net cookie操作实例。
 

复制代码 代码示例:

//写入cookie
protected void button1_click(object sender, eventargs e)
{
    httpcookie cookie=new httpcookie("mycook");//初使化并设置cookie的名称
    datetime dt=datetime.now;
    timespan ts = new timespan(0, 0, 1,0,0);//过期时间为1分钟
    cookie.expires = dt.add(ts);//设置过期时间
    cookie.values.add("userid", "userid_value");
    cookie.values.add("userid2","userid2_value2");
    response.appendcookie(cookie);
    //输出该cookie的所有内容
    //response.write(cookie.value);//输出为:userid=userid_value&userid2=userid2_value2
  }

//读取cookie
protected void button2_click(object sender, eventargs e)
{
// httpcookie cokie = new httpcookie("mycook");//初使化
if (request.cookies["mycook"]!=null)
{
 //response.write("cookie中键值为userid的值:" + request.cookies["mycook"]["userid"]);//整行
 //response.write("cookie中键值为userid2的值" + request.cookies["mycook"]["userid2"]);
 response.write(request.cookies["mycook"].value);//输出全部的值
}
}

//修改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);
}
}