依赖
using System.Web;
设置Cookie
1.新建Cookie对象
HttpCookie cookie = new HttpCookie("UserInfo");
“UserInfo”是这个Cookie的名称
2.设置Cookie有效时间
cookie.Expires = DateTime.Now.AddDays(15);
3.设置Cookie属性与值
cookie.Values["UserName"] = "萌狼蓝天";
“UserName”是UserInfo的熟悉,“萌狼蓝天”是该属性对应的值
为了避免中文乱码,应该对值进行URL编码(使用时需要URL解码)
cookie.Values["UserName"] = HttpUtility.UrlEncode("萌狼蓝天");
获取Cookie
1.获取Cookie对象
HttpCookie cookie = Request.Cookies["UserInfo"];
UserInfo 是设置的Cookie名
2.获取Cookie值
HttpCookie cookie = Request.Cookies["UserInfo"]; lblUserName.Text = cookie.Values["UserName"]
UserName是UserInfo的属性
为了避免中文乱码问题,应在设置时使用URL编码,则获取时,需使用URL解码
lblUserName.Text = HttpUtility.UrlDecode(cookie.Values["UserName"]);
判断是否存在某个Cookie
//取cookie HttpCookie cookie = Request.Cookies["UserInfo"]; //判断Cookie是否为空 if (cookie != null) { //如果不为空,说明有Cookie,此时跳转到userticket.aspx Response.Redirect("userticket.aspx", false); }