无法为cookie附加价值

时间:2015-04-15 03:09:07

标签: asp.net vb.net cookies

我的cookie正在填充第一页面的值。 但是,当我尝试通过下面的代码稍后使用其他值更新它,然后刷新页面时,它只显示初始值。 为什么我不能更新cookie?

If Request.Cookies("lastviewed") Is Nothing Then
    Dim cookie As HttpCookie = New System.Web.HttpCookie("lastviewed", Request.RawUrl + "|" + photo + "|" + title + "|" + price)
    HttpContext.Current.Response.Cookies.Add(cookie)
Else
    lastviewed = Server.UrlDecode(Request.Cookies("lastviewed").Value)
    If Not lastviewed.Contains(Request.RawUrl + "|") Then
        If lastviewed.Split(";").Length < 5 Then
            If lastviewed.Split(";").Length > 0 Then
               lastviewed = lastviewed + ";" + Request.RawUrl + "|" + photo + "|" + title + "|" + price
            Else
                lastviewed = Request.RawUrl + "|" + photo + "|" + title + "|" + price
            End If
            'this part where I want to ADD a new value to the cookie does not seem to work
            Dim cookie As New System.Web.HttpCookie("lastviewed", lastviewed)
            HttpContext.Current.Response.Cookies.Add(cookie)
        End If
    End If
End If

1 个答案:

答案 0 :(得分:1)

这是因为cookie无法接受这些字符:

空白,DQUOTE,逗号,分号和反斜杠。

因此,您可以更改分割字符,例如 @

If lastviewed.Split("@").Length < 5 Then
    If lastviewed.Split("@").Length > 0 Then
        lastviewed = lastviewed + "@" + Request.RawUrl + "|" + photo + "|" + Title + "|" + price

再试一次。