当前位置: 编程技术>.net/c#/asp.net
asp.net操作cookie实例代码
来源: 互联网 发布时间:2014-08-30
本文导语: 写入cookie 代码如下: HttpCookie cookie = new HttpCookie("Info");//定义cookie对象以及名为Info的项 DateTime dt = DateTime.Now;//定义时间对象 TimeSpan ts=new TimeSpan(1,0,0,0);//cookie有效作用时间,具体查msdn cookie.Expires = dt.Add(ts);//添加作用时间 cookie...
写入cookie
代码如下:
HttpCookie cookie = new HttpCookie("Info");//定义cookie对象以及名为Info的项
DateTime dt = DateTime.Now;//定义时间对象
TimeSpan ts=new TimeSpan(1,0,0,0);//cookie有效作用时间,具体查msdn
cookie.Expires = dt.Add(ts);//添加作用时间
cookie.Values.Add("user","cxbkkk");//增加属性
cookie.Values.Add("userid","1203");
Response.AppendCookie(cookie);//确定写入cookie中
DateTime dt = DateTime.Now;//定义时间对象
TimeSpan ts=new TimeSpan(1,0,0,0);//cookie有效作用时间,具体查msdn
cookie.Expires = dt.Add(ts);//添加作用时间
cookie.Values.Add("user","cxbkkk");//增加属性
cookie.Values.Add("userid","1203");
Response.AppendCookie(cookie);//确定写入cookie中
读取cookie
代码如下:
if(Request.Cookies["Info"]!=null)
{
string temp=Convert.ToString(Request.Cookies["Info"].Values["user"])+" "+Convert.ToString(Request.Cookies["Info"].Values["userid"]);
//读全部就用Request.Cookies["Info"].Value
if(temp=="")
{
Response.Write("空");
}
else
Response.Write(temp);
}
else
{
Response.Write("error");
}
{
string temp=Convert.ToString(Request.Cookies["Info"].Values["user"])+" "+Convert.ToString(Request.Cookies["Info"].Values["userid"]);
//读全部就用Request.Cookies["Info"].Value
if(temp=="")
{
Response.Write("空");
}
else
Response.Write(temp);
}
else
{
Response.Write("error");
}
修改cookie
代码如下:
Response.Cookies["Info"]["user"] = "2";
Response.Cookies["Info"].Expires = DateTime.Now.AddDays(1);
Response.Cookies["Info"].Expires = DateTime.Now.AddDays(1);
删除cookie下的属性
代码如下:
HttpCookie acookie=Request.Cookies["Info"];
acookie.Values.Remove("userid");
acookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(acookie);
acookie.Values.Remove("userid");
acookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(acookie);
删除所有cookie(设置过期时间为现在即可)
代码如下:
int limit=Request.Cookies.Count - 1;
for(int i=0;i
for(int i=0;i