我想将用户最近访问的页面存储在 cookie 中。它有 2 个部分,PageTitle 和 URL。我使用下面的代码,但它只是在第一页加载中保存一个值,而不在其他页面加载中更改它。
if (Request.Cookies["latestvisit"] == null)
{
HttpCookie myCookie = new HttpCookie("latestvisit");
myCookie.Expires = DateTime.Now.AddYears(1);
myCookie.Values[title] = System.Web.HttpUtility.UrlEncode(URL);
Response.Cookies.Add(myCookie);
}
else
{
System.Collections.Specialized.NameValueCollection cookieCollection = Request.Cookies["latestvisit"].Values;
string[] CookieTitles = cookieCollection.AllKeys;
//mj-y: If the url is reapeated, move it to end(means make it newer by removing it and adding it again)
string cookieURL = "";
foreach (string cookTit in CookieTitles)
{
cookieURL = System.Web.HttpUtility.UrlDecode(Request.Cookies["latestvisit"].Values[cookTit]);
if (cookieURL == URL)
{
cookieCollection.Remove(cookTit);
cookieCollection.Set(title, URL);
return;
}
}
//mj-y: If it was not repeated ...
if (cookieCollection.Count >15) // store just 15 item
cookieCollection.Remove(CookieTitles[0]);
cookieCollection.Set(title, URL);
}
当然我想对 url 进行编码和解码,所以用户无法确定 cookie 的内容,我该怎么做?