If Not Request.Cookies("userName") Is Nothing Then Label1.Text = Server.HtmlEncode(Request.Cookies("userName").Value) End If
If Not Request.Cookies("userName") Is Nothing Then Dim aCookie As HttpCookie = Request.Cookies("userName") Label1.Text = Server.HtmlEncode(aCookie.Value) End If
注意:由于不同的浏览器保存 Cookie 的方式也不同,所以同一台计算机上的不同浏览器不一定能够相互读取各自的 Cookie。例如,如果使用 Internet Explorer 测试一个页面,然后再使用其他浏览器进行测试,那么后者就不会找到 Internet Explorer 保存的 Cookie。当然,大多数人一般都是使用同一种浏览器进行 Web 交互的,因此在大多数情况下不会出现问题。但有时还是会遇到问题,比如您要测试应用程序 对浏览器的兼容性。
读取 Cookie 中子键值的方法与设置该值的方法类似。以下是获取子键值的一种方法:
If Not Request.Cookies("userInfo") Is Nothing Then Label1.Text = _ Server.HtmlEncode(Request.Cookies("userInfo")("userName")) Label2.text = _ Server.HtmlEncode(Request.Cookies("userInfo")("lastVisit")) End If
If Not Request.Cookies("userInfo") Is Nothing Then Dim UserInfoCookieCollection As _ System.Collections.Specialized.NameValueCollection UserInfoCookieCollection = Request.Cookies("userInfo").Values Label1.Text = Server.HtmlEncode(UserInfoCookieCollection("userName")) Label2.Text = Server.HtmlEncode(UserInfoCookieCollection("lastVisit")) End If