ASP.NET设置单个子项会删除其他子项

时间:2012-06-29 14:12:41

标签: asp.net vb.net visual-studio-2010 cookies

我正在使用一个大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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:0)

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

如果您只编辑其中一个子键,则必须使用以下代码:

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

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