Cookie的创建使用和删除
最近发现好多东西都没记录下来,有点忘记了,借此记录一下。
创建Cookie
1 HttpCookie myCookie = new HttpCookie("UserSettings");
2 myCookie["Font"] = "Arial";
3 myCookie["Color"] = "Blue";
4 myCookie.Expires = DateTime.Now.AddDays(1d);
5 Response.Cookies.Add(myCookie);
效果:
设置cookie的路径,应该是用来限制myCookie的访问范围。
1 myCookie.Path = "test";
效果:
使用Cookie:
1 if (Request.Cookies["UserSettings"] != null)
2 {
3 string userSettings;
4 if (Request.Cookies["UserSettings"]["Font"] != null)
5 { userSettings = Request.Cookies["UserSettings"]["Font"]; }
6 }
7
删除Cookie:
1
2 if (Request.Cookies["UserSettings"] != null)
3 {
4 HttpCookie myCookie = new HttpCookie("UserSettings");
5 myCookie.Expires = DateTime.Now.AddDays(-1d);
6 Response.Cookies.Add(myCookie);
7 }
设置过期即可删除Cookie。