ASP.NET对cookies的操作方法
cookie是一段文本信息,在客户端存储 cookie 是 asp.net 的会话状态将请求与会话关联的方法之一。cookie 也可以直接用于在请求之间保持数据,但数据随后将存储在客户端并随每个请求一起发送到服务器。浏览器对 cookie 的大小有限制,因此,只有不超过 4096 字节才能保证被接受。
//方式1:
response.cookies["username"].value="mike";
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="mike";
response.cookies["userinfo1"]["last"].value="a";
response.cookies["userinfo1"].expires=datetime.maxvalue;
//方式2:
httpcookie cookie = new httpcookie("userinfo1");
cookie.values["name"]="mike";
cookie.values["last"]="a";
cookie.expires=datetime.maxvalue; 
response.cookies.add(cookie);
         读取cookie 
         internet explorer 将站点的 cookie 保存在文件名格式为 <user>@<domain>.txt 的文件中,其中 <user> 是您的帐户名。
         注意:在获取cookie的值之前,应该确保该 cookie 确实存在。否则,您将得到一个异常
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[i];
     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>");        
     }
}
    运行此代码时,可看到一个名为“asp.net_sessionid”的cookie,asp.net用这个 cookie 来保存您的会话的唯一标识符。 
修改 cookie 
修改的方法与创建方法相同
删除 cookie 
将其有效期设置为过去的某个日期。当浏览器检查 cookie 的有效期时,就会删除这个已过期的 cookie。
     HttpCookie cookie = new HttpCookie("userinfo1");
cookie.Expires=DateTime.Now.AddDays(-30); 
Response.Cookies.Add(cookie);
 
                    
                     
                    
                 
                    
                
 
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号