在cookie中存储用户最新访问页面

时间:2013-10-27 05:44:06

标签: c# cookies asp.net-4.0

我想将用户最近访问过的网页存储在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);
    }

当然我想对网址进行编码并对其进行解码,因此用户无法确定Cookie的内容,我该怎么办呢?

1 个答案:

答案 0 :(得分:2)

试试这个:

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
{
    var myCookie = Request.Cookies["latestVisit"];
    var cookieCollection = myCookie.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, System.Web.HttpUtility.UrlEncode(URL));
            Response.SetCookie(myCookie);
            return;
        }
    }
    //mj-y: If it was not repeated ...
    cookieCollection.Set(title, System.Web.HttpUtility.UrlEncode(URL));
    if (cookieCollection.Count > 15) // store just 15 item         
        cookieCollection.Remove(CookieTitles[0]);
    Response.SetCookie(myCookie);
}

作为一种安全的做法,我还建议您在将title变量添加到值集合之前对其进行编码,例如:

myCookie.Values[System.Web.HttpUtility.UrlEncode(title)] 
    = System.Web.HttpUtility.UrlEncode(URL);

cookieCollection.Set(System.Web.HttpUtility.UrlEncode(title), 
    System.Web.HttpUtility.UrlEncode(URL));