以下示例是对前一示例的修改。示例中使用 HasKeys 属性来测试子键,如果检测到子键,就从 Values 集合中获取子键:
复制代码 代码如下:
Dim i As Integer
Dim j As Integer
Dim output As String = ""
Dim aCookie As HttpCookie
Dim subkeyName As String
Dim subkeyValue As String
For i = 0 To Request.Cookies.Count - 1
aCookie = Request.Cookies(i)
output &= "名称 = " & aCookie.Name & "<br>"
If aCookie.HasKeys Then
For j = 0 To aCookie.Values.Count - 1
subkeyName = Server.HtmlEncode(aCookie.Values.AllKeys(j))
subkeyValue = Server.HtmlEncode(aCookie.Values(j))
output &= "子键名称 = " & subkeyName & "<br>"
output &= "子键值 = " & subkeyValue & "<br><br>"
Next
Else
output &= "值 = " & Server.HtmlEncode(aCookie.Value) & "<br><br>"
End If
Next
Label1.Text = output
您也可以把子键作为 NameValueCollection 对象进行提取,如下所示:
复制代码 代码如下:
If aCookie.HasKeys Then
Dim CookieValues As _
System.Collections.Specialized.NameValueCollection = aCookie.Values
Dim CookieValueNames() As String = CookieValues.AllKeys
For j = 0 To CookieValues.Count – 1
subkeyName = Server.HtmlEncode(CookieValueNames(j))
subkeyValue = Server.HtmlEncode(CookieValues(j))
output &= "子键名称 = " & subkeyName & "<br>"
output &= "子键值 = " & subkeyValue & "<br><br>"
Next
Else
output &= "值 = " & aCookie.Value & "<br><br>"
End If
注意:之所以调用 Server.HtmlEncode 方法,只是因为我要在页面上显示 Cookie 的值。如果您只是测试 Cookie 的值,就不必在使用前对其进行编码。
修改和删除 Cookie
有时,您可能需要修改某个 Cookie,更改其值或延长其有效期。(请记住,由于浏览器不会把有效期信息传递到服务器,所以您无法读取 Cookie 的过期日期。)
当然,实际上您并不是直接更改 Cookie。尽管您可以从 Request.Cookies 集合中获取 Cookie 并对其进行操作,但 Cookie 本身仍然存在于用户硬盘上的某个地方。因此,修改某个 Cookie 实际上是指用新的值创建新的 Cookie,并把该 Cookie 发送到浏览器,覆盖客户机上旧的 Cookie。
以下示例说明了如何更改用于储存站点访问次数的 Cookie 的值:
复制代码 代码如下:
Dim counter As Integer
If Request.Cookies("counter") Is Nothing Then
counter = 0
Else
counter = CInt(Request.Cookies("counter").Value)
End If
counter += 1
Response.Cookies("counter").Value = counter.ToString
Response.Cookies("counter").Expires = DateTime.Now.AddDays(1)
或者:
Dim ctrCookie As HttpCookie
Dim counter As Integer
If Request.Cookies("counter") Is Nothing Then
ctrCookie = New HttpCookie("counter")
Else
ctrCookie = Request.Cookies("counter")
End If
counter = CInt(ctrCookie.Value) + 1
ctrCookie.Value = counter.ToString
ctrCookie.Expires = DateTime.Now.AddDays(1)
Response.Cookies.Add(ctrCookie)