我正在尝试保存一个cookie然后阅读它。无法编译,因为行的代码中有错误(readcookie[....])-
Response.Write("USERNAME: " + readCookie["userInfo"]["userName"].ToString());
它说 - “string.this[int] 的最佳重载方法匹配具有无效参数。
如果我写,
Response.Write("USERNAME: " + readCookie["userInfo"][0].ToString());
然后我可以编译。它在 save_click 上显示“数据已保存”消息,但在 read_click 上显示错误 - 对象引用无效。它是否首先正确保存了 cookie。我怎么能从中读出。这是我的代码:
protected void btnSaveCookie_Click(object sender, EventArgs e)
{
HttpCookie myCookie = new HttpCookie("userInfo");
myCookie.Values["userName"] = "Patrick";
myCookie.Values["lastVisit"] = DateTime.Now.ToString();
Response.Cookies.Add(myCookie);
Response.Write("Data Stored Into Cookie....");
}
protected void btnReadCookie_Click(object sender, EventArgs e)
{
HttpCookie readCookie = Request.Cookies.Get("userInfo");
Response.Write("USERNAME: " + readCookie["userInfo"]["userName"].ToString());
Response.Write("LAST VISIT: " + readCookie["userInfo"]["lastVisit"].ToString());
}