內存cookie,是指沒有設在cookie的Expires的屬性,此時cookie將停留在客戶端的內存中,只有在該IE窗口中從“文件-新建- 窗口”打開的新的IE窗和由form的target屬性為_blank產生的新的IE窗口才共享同一個cookie信息。IE,Chome的選項卡都共享同一個cookie信息。
硬盤cookie,是指在你設置了cookie的Expires屬性,此時cookie將保存到你的硬盤上,Win7是在C:\Users\Administrator\AppData\Roaming\Microsoft\Windows\Cookies 下面(如果你是Administrator賬號的話)。此時所有的窗口將共享同一個名字的cookie。
針對內存cookie,用fiddler可以看到cookie 沒有 exprires這個屬性,只要關掉ie再重新打開頁面將會丟失(注:如果不關掉原來的ie窗口,新打開ie訪問頁面cookie還是會在)。
如果內存cookie沒有指定域,那么可以在多個不同的站點間共享內存cookie
MVC測試代碼 Controller 文件如下:
public ActionResult WriteCookie() { HttpCookie cookie = new HttpCookie("Name1", "Nick"); cookie.Expires = DateTime.Now.AddDays(1); cookie.Domain = "MVCTest2"; Response.Cookies.Add(cookie); return View(); } public ActionResult ReadCookie() { if (Request.Cookies["Name1"] != null) { ViewData["Cookie1"] = Request.Cookies["Name1"].Value; } return View(); } public ActionResult WriteInMemoryCookie() { HttpCookie cookie = new HttpCookie("Name2", "Nick In Memory"); cookie.Domain = "MVCTest2"; Response.Cookies.Add(cookie); return View(); } public ActionResult ReadInMemoryCookie() { if (Request.Cookies["Name2"] != null) { ViewData["Cookie2"] = Request.Cookies["Name2"].Value; } return View(); }
4個cshtml如下
ReadCookie.cshtml
@{ Layout = null; } <!DOCTYPE html> <html> <head> <title>ReadCookie</title> </head> <body> <div> @if(ViewData["Cookie1"]==null) { <text>No Cookie exists. </text> } else { <text>Cookie</text> @ViewData["Cookie1"].ToString(); } </div> </body> </html>
ReadInMemoryCookie.cshtml
@{ Layout = null; } <!DOCTYPE html> <html> <head> <title>ReadInMemoryCookie</title> </head> <body> <div> @if(ViewData["Cookie2"]==null) { <text>No In Memory Cookie exists. </text> } else { <text>In Memory Cookie</text> @ViewData["Cookie2"].ToString(); } </div> </body> </html>
WriteCookie.cshtml
@{ Layout = null; } <!DOCTYPE html> <html> <head> <title>Cookie</title> </head> <body> <div> Write Cookie Successfully. </div> </body> </html>
WriteInMemoryCookie.cshtml
@{ Layout = null; } <!DOCTYPE html> <html> <head> <title>WriteInMemoryCookie</title> </head> <body> <div> Write In-Memory Cookie Successfully. </div> </body> </html>