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