刷新页面后,Vb.net cookie成为会话

时间:2017-05-15 14:44:53

标签: asp.net vb.net cookies

我正在尝试设置一个cookie,如果存在则更新它。在初始设置上,cookie看起来很好并且有到期日期,但如果我刷新该页面,则cookie会变为会话。

开集:enter image description here 刷新enter image description here

任何想法为什么?

Function writeReadArticleToCookie(ByVal id As Integer) As String()

        Dim sarr As String()

        Dim cookie As HttpCookie
        cookie = Request.Cookies("read_articles")
        If cookie Is Nothing
            cookie = New HttpCookie("read_articles")
            cookie.Path = "/"
            cookie.Value = id.ToString() & ","
            cookie.Expires = DateTime.Now.AddHours(6)
            sarr  = cookie.Value.Split(",")
        Else

            sarr  = cookie.Value.Split(",")
            If not sarr.Contains(id.ToString()) Then
              cookie.Value = cookie.Value & id.ToString() & ","
              cookie.Path = "/"

              sarr  = cookie.Value.Split(",")

            End If

        End If

        Response.Cookies.Add(cookie)

        Return sarr

    End Function

1 个答案:

答案 0 :(得分:0)

经典错误。我正在更新请求cookie,而不是响应一个。 这是有效的代码

 Function writeReadArticleToCookie(ByVal id As Integer) As String()


        Dim sarr As String()

        Dim cookie As HttpCookie
        cookie = Request.Cookies("read_articles")
        If cookie Is Nothing
            cookie = New HttpCookie("read_articles")
            cookie.HttpOnly = true
            cookie.Value = id.ToString()
            cookie.Expires = DateTime.Now.AddHours(6)
            sarr  = cookie.Value.Split(",")
             Response.Cookies.Add(cookie)
        Else


            sarr = cookie.Value.Split(",")
            If not sarr.Contains(id.ToString()) Then


                Response.Cookies("read_articles").Value = cookie.Value & "," & id.ToString()
                Response.Cookies("read_articles").Expires = DateTime.Now.AddHours(6)

                sarr = Response.Cookies("read_articles").Value.Split(",")

            End If

        End If



        Return sarr

    End Function