4 回答
TA贡献1797条经验 获得超6个赞
参考代码如下:
//如果请求的Cookie对象为空
if (Request.Cookies["userCookie"] == null)
{
//创建一个Cookie对象
HttpCookie userCookie = new HttpCookie("userCookie");
//给对象赋值
userCookie.Values["userName"] =
userInfo.UserName.ToString();
userCookie.Values["lastVist"] =
DateTime.Now.ToString();
userCookie.Values["count"] = "1";
//设置对象的过期时间
userCookie.Expires = DateTime.Now.AddDays(30);
//添加到Cookies集合
Response.Cookies.Add(userCookie);
}
//不为空的情况
else
{
int counter =
Convert.ToInt32
(Request.Cookies["userCookie"]["count"]) + 1;
HttpCookie userCookie =
new HttpCookie("userCookie");
userCookie.Values["userName"] =
userInfo.UserName.ToString();
userCookie.Values["lastVist"] =
DateTime.Now.ToString();
userCookie.Values["count"] =
counter.ToString();
userCookie.Expires =
DateTime.Now.AddDays(30);
Response.Cookies.Add(userCookie);
}
TA贡献1772条经验 获得超8个赞
使用Response将cookie写入客户端,而使用Request读取客户端的cookie。所以,第二个页面中读取cookie应写成下面这样:
HttpCookie temp = Request.Cookies["newcookie"];
添加回答
举报