一、添加cookie
C# 代码 复制//方式1:
Response.Cookies["username"].value="gggg";
Response.Cookies["username"].Expires=DateTime.MaxValue;
//方式2:
HttpCookie acookie = new HttpCookie("last");
acookie.Value="a";
acookie..Expires=DateTime.MaxValue;
Response.Cookies.Add(acookie);
//多值Cookie的写法
//方式1:
Response.Cookies["userinfo1"]["name"].value="aaa";
Response.Cookies["userinfo1"]["last"].value="a";
Response.Cookies["userinfo1"].Expires=DateTime.MaxValue;
//方式2:
HttpCookie cookie = new HttpCookie("userinfo1");
cookie.Values["name"]="aaa";
cookie.Values["last"]="a";
cookie.Expires=DateTime.MaxValue;
//cookie.Expires = System.DateTime.Now.AddDays(1);//设置过期时间 1天
Response.Cookies.Add(cookie);
二、读取Cookie
Internet Explorer 将站点的 Cookie 保存在文件名格式为 <user>@<domain>.txt 的文件中,其中 <user> 是您的帐户名。
C# 代码 复制if (Request.Cookies["userName"]!=null)
{
string str = Request.Cookies("userName").Value;
}
//多值Cookie的读取
if (Request.Cookies["userInfo1"]!=null )
{
string name=Request.Cookies["userInfo1"]["name"];
string last=Request.Cookies["userInfo1"]["last"];
}
//读取 Cookie 集合
for(int i = 0 ;i<Request.Cookies.Count ;i++)
{
HttpCookie cookies = Request.Cookies;
Response.Write("name="+cookies.Mame+"<br/>");
if (cookies.HasKeys )//是否有子键
{
System.Collections.Specialized.NameValueCollection NameColl
= aCookie.Values ;
for(int j=0;j<NameColl.Count;j++)
{
Response.Write("子键名="+ NameColl.AllKey[j] +"<br/>");
Response.Write("子键值="+ NameColl[j] +"<br/>");
}
}
else
{
Response.Write("value="+cookies.Value+"<br/>");
}
}
注意:在获取Cookie的值之前,应该确保该 Cookie 确实存在。否则,您将得到一个异常
三、修改 Cookie
修改的方法与创建方法相同
四、删除 Cookie
将其有效期设置为过去的某个日期。当浏览器检查 Cookie 的有效期时,就会删除这个已过期的 Cookie。
C# 代码 复制//删除cookie下的属性
HttpCookie acookie=Request.Cookies["Info"];
acookie.Values.Remove("userid");
acookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.A
新闻热点
疑难解答