Cookie是一段文本信息,在客戶端存儲(chǔ) Cookie 是 ASP.NET 的會(huì)話狀態(tài)將請(qǐng)求與會(huì)話關(guān)聯(lián)的方法之一。Cookie 也可以直接用于在請(qǐng)求之間保持?jǐn)?shù)據(jù),但數(shù)據(jù)隨后將存儲(chǔ)在客戶端并隨每個(gè)請(qǐng)求一起發(fā)送到服務(wù)器。瀏覽器對(duì) Cookie 的大小有限制,因此,只有不超過 4096 字節(jié)才能保證被接受。
//方式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);
//方式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;
//cookie.Expires = System.DateTime.Now.AddDays(1);//設(shè)置過期時(shí)間 1天
Response.Cookies.Add(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 ;iRequest.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;jNameColl.Count;j++)
{
Response.Write("子鍵名="+ NameColl.AllKey[j] +"br/>");
Response.Write("子鍵值="+ NameColl[j] +"br/>");
}
}
else
{
Response.Write("value="+cookies.Value+"br/>");
}
}
運(yùn)行此代碼時(shí),可看到一個(gè)名為“ASP.NET_SessionId”的Cookie,ASP.NET用這個(gè) Cookie 來保存您的會(huì)話的唯一標(biāo)識(shí)符。
HttpCookie cookie = new HttpCookie("userinfo1");
cookie.Expires=DateTime.Now.AddDays(-30);
Response.Cookies.Add(cookie);
修改cookie
Response.Cookies["Info"]["user"] = "2";
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); //刪除所有cookie,就是設(shè)置過期時(shí)間為現(xiàn)在就行了
int limit=Request.Cookies.Count - 1;
for(int i=0;ilimit;i++)
{
acookie = Request.Cookies(i)
acookie.Expires = DateTime.Now.AddDays(-1)
Response.Cookies.Add(acookie)
}
cookie.Domain = ".主域名";//例如.keleyi.com
cookie.Path = "/";
Cookie.Expires AddDays(-1)是立即過期