2015-04-20 47 views
2

我正在尝试创建一个存储用户查看的属性列表的cookie。最近浏览过的Cookie

我创建了一个测试,它的工作部分。目前,每次我访问一个页面时,它都会从URL中提取属性ID,并创建一个包含该URL的新字符串,如果cookie已经存在,它会将该属性ID附加到该页面上。

@{ 
    var rPropertyId = UrlData[0].AsInt(); 

    if(rPropertyId > 0){ 
     if (Request.Cookies["viewed_properties"] != null){ 
      var value = Request.Cookies["viewed_properties"].Value.ToString(); 
      var value1 = value + "." + rPropertyId; 
      var newcookievalue = String.Join(".", value1.Split(new Char[] {'.'}).Distinct()); 
      Response.Cookies["viewed_properties"].Value = newcookievalue; 
      Response.Cookies["viewed_properties"].Expires = DateTime.Now.AddYears(1); 
     } else { 
      Response.Cookies["viewed_properties"].Value = rPropertyId.ToString(); 
      Response.Cookies["viewed_properties"].Expires = DateTime.Now.AddYears(1);    
     } 
    } 
} 

@if (Request.Cookies["viewed_properties"] != null){ 
    var mylist = Request.Cookies["viewed_properties"].Value.Split(new Char[] {'.'}); 
    foreach (var i in mylist) 
    { 
     <p>@i</p> 
    } 
} 

这个过程不会采取什么样的考虑是,如果用户访问相同的属性不止一次,我还是想在cookie中只有1个是ID的条目。我将如何检查这个,将其转换为数组?

回答

2

Enumerable.Distinct将确保您没有重复。

喜欢的东西:

var newCookieValue = 
     String.Join(".",   
      currentCookieValue.Split(new Char[] {'.'}).Distinct()); 

为最新添加到末尾 - 一种选择是除去第一和以后添加:

.... 
    currentCookieValue.Split(new Char[] {'.'}) 
     .Where(s => s != newStringValueToAdd) 
     .Distinct() 
     .ToList() 
     .Add(newStringValueToAdd) 

边注:cookie的值具有相对小的长度限制(What is the maximum size of a web browser's cookie's key? ),所以要小心添加任意数量的项目到单个cookie。

+0

好吧,所以添加“独特”功能可以确保没有重复,这很好。但是,如果它找到重复的,它不会将明确的条目添加到列表的末尾? – Gavin5511

+0

例如,如果我浏览属性1,然后属性2,然后属性3,然后属性1再次,我希望“1”在列表的末尾?这是否有超载? – Gavin5511

+0

@ Gavin5511没有超载,你必须删除/添加你的自我(添加示例)。 –