2013-10-27 76 views
2

我想將用戶最近訪問過的頁面存儲在cookie中。它有2個部分,PageTitle和URL。 我使用下面的代碼,但它只是在首頁加載時保存一個值,並且不會在其他頁面加載中更改它。在cookie中存儲用戶最近的訪問頁面

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的內容,我該怎麼辦呢?

+0

如何設置'title'和'URL'變量? –

回答

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)); 
相關問題