2

我正在使用一个大 cookie 的子键来存储多个帮助文本的隐藏状态。但是如果更新了单个子项,则所有其他子项都将被删除。我是否应该始终同时更新给定 cookie 的所有子键来解决这个问题?

这是我目前有问题的功能。

' Store cookie_value of cookie_name  .
sub store_string( cookie_value , cookie_name  )
    ' Sets cookie cookie_name to cookie_value.
        response.Cookies( "UserSettings" )( cookie_name ) = cookie_value 
        response.Cookies( "UserSettings").Expires = datetime.now.adddays(365*10)  ' 10 years.  The hardware won't last that long!
end sub



' Retrieve stored cookie_name.
function restore_string( byval cookie_name  ) 
    ' Returns cookie named cookie_name.
        If  Request.Cookies( "UserSettings") Is Nothing Then
            return ""
        else
            cookie_value =  Server.HtmlEncode(Request.Cookies( "UserSettings" )( cookie_name ))
            return   cookie_value
        end if
end function
4

2 回答 2

1

我遇到了同样的问题,看起来这已经在 asp.net 论坛上得到了回答: http ://forums.asp.net/t/1819596.aspx/1

这是代码片段:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Me.Label1.Text = DateTime.Now.ToString()
    'add cookie
    If Not Me.IsPostBack Then
        Dim aCookie As New HttpCookie("userInfo")
        aCookie.Values("userName") = "UserName"
        aCookie.Values("lastVisit") = DateTime.Now.ToString()
        aCookie.Expires = DateTime.Now.AddDays(1)
        Response.Cookies.Add(aCookie)
    End If
End Sub


Protected Sub Button1_Click(sender As Object, e As EventArgs)
    ' update subkey : "lastVisit"
    Dim cookie As HttpCookie = Request.Cookies("userInfo")
    cookie("lastVisit") = DateTime.Now.ToString()
    cookie.Expires = DateTime.Now.AddDays(1)
    Response.Cookies.Add(cookie)

End Sub

Protected Sub Button2_Click(sender As Object, e As EventArgs)
    ' show all subkey values
    Response.Write(Request.Cookies("userInfo")("userName"))
    Response.Write(Request.Cookies("userInfo")("lastVisit"))
End Sub
于 2012-11-26T23:23:51.700 回答
0

我花了几天时间试图解决这个问题,最后得出了这个解决方案:

如果您只编辑 1 个子项,则必须使用代码:

Dim cookieCode As HttpCookie = _contxt.Request.Cookies(COOKIE_NAME)
cookieCode.Values.Set(KEY, ivalue) 
Response.Cookies.Add(cookieCode)

SET 命令将只更新子项。使用完整响应方法将覆盖其他子项。

于 2014-08-27T19:24:08.670 回答