public ActionResult Index() { #region 写入Cookies HttpCookie cookie = new HttpCookie("CookieName");//初使化并设置Cookie的名称 DateTime dt = DateTime.Now; //获取当前时间 TimeSpan ts = new TimeSpan(0, 0, 1, 0, 0);//过期时间为1分钟 cookie.Expires = dt.Add(ts);//设置过期时间 cookie.Values.Add("UserName", "admin"); cookie.Values.Add("Pwd", "123456"); Response.AppendCookie(cookie); //响应一个Cookies //在网页Cookies中的Name 是CookieName;Value是UserName=admin&Pwd=123456 HttpCookie cookie1 = new HttpCookie("MaxMin"); //添加第二个cookies cookie1.Expires = dt.Add(ts);//设置过期时间 cookie1.Values.Add("Test", "aaaaaa"); Response.AppendCookie(cookie1); //响应一个Cookies //网页中 NAME 是MaxMin ; Value 是Test=aaaaaa #endregion #region 读取Cookies HttpCookie cokie = new HttpCookie("MyCook");//初使化 if (Request.Cookies["CookieName"] != null) { //Response.Write("Cookie中键值为userid的值:" + Request.Cookies["MyCook"]["userid"]);//整行 //Response.Write("Cookie中键值为userid2的值" + Request.Cookies["MyCook"]["userid2"]); Response.Write(Request.Cookies["CookieName"].Value);//输出全部的值 } #endregion #region 修改Cookies //获取客户端的Cookie对象 HttpCookie cok = Request.Cookies["CookieName"]; if (cok != null) { //修改Cookie的两种方法 cok.Values["userid"] = "alter-value"; cok.Values.Set("userid", "alter-value"); //往Cookie里加入新的内容 cok.Values.Set("newid", "newValue"); Response.AppendCookie(cok); } #endregion #region 删除Cookies HttpCookie Cookie = Request.Cookies["CookieName"]; if (Cookie != null) { Cookie.Values.Remove("userid");//移除键值为userid的值 } else { TimeSpan ts1 = new TimeSpan(-1, 0, 0, 0); Cookie.Expires = DateTime.Now.Add(ts);//删除整个Cookie,只要把过期时间设置为现在 } Response.AppendCookie(Cookie); #endregion HttpCookie A = Request.Cookies["Mxx"]; if (A==null) { return Content(null); } else { return Content(A.Name); } }
from C# Cookies设置和读取 - enych - 博客园 (cnblogs.com)