2013-10-27 2 views
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을 코딩 및 디코딩 할 물론, 그래서 사용자의 캔트 쿠키의 내용을 결정

, 내가 그것을 어떻게 할 수 있습니까?

+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)); 
관련 문제