【问题标题】:Vb.net cookie becomes session after refreshing page刷新页面后vb.net cookie变成会话
【发布时间】:2017-05-17 15:05:34
【问题描述】:

我正在尝试设置一个 cookie,如果存在则更新它。在初始设置中,cookie 看起来不错并且有过期日期,但是如果我刷新该页面,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.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

【问题讨论】:

  • 你没有在else中设置Expire,所以cookie使用默认的Expire,即Session。
  • @mattfei 实际上,问题是我正在更新请求而不是响应 cookie。

标签: asp.net vb.net cookies


【解决方案1】:

经典错误。我正在更新请求 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-21
    • 1970-01-01
    • 2014-07-20
    • 2013-12-22
    • 1970-01-01
    相关资源
    最近更新 更多