我正在尝试设置一个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
答案 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