c# - 最近查看的 Cookie

标签 c# razor cookies webmatrix

我正在尝试创建一个 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 中包含该 ID 的 1 个条目。我如何检查它,将其转换为数组?

最佳答案

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 添加任意数量的项目。

关于c# - 最近查看的 Cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29752189/

相关文章:

c# - 从文本框计数,asp.net

c# - 文件上传 ASP.NET MVC

asp.net-mvc - 如何在 Html.RenderAction (MVC3) 中发送模型对象

java - HSTS super Cookie 实现

javascript - 如何从 Ajax 调用修改 Cookie

javascript - 检查cookie是否仍然有效

c# - 无法加载文件或程序集 XXX 或其依赖项之一。找到的程序集的 list 定义与程序集引用不匹配

c# - 更新linq中的单行

asp.net-mvc - Razor View 引擎: An expression tree may not contain a dynamic operation

asp.net-mvc - 如何使用 displayfor 从模型中获取枚举到 View 中