内存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>