读取 cookie
当浏览器向服务器发送请求时,该服务器的 cookie 会与请求一起发送。在asp.net 应用程序中,您可以使用 request 对象来读取 cookie。request 对象的结构与 response 对象的结构基本相同,所以从 request 对象中读取 cookie 的方法与向response 对象中写入 cookie 的方法非常类似。以下示例显示了两种方法,目的都是获取名为“username”的 cookie 的值并将值显示在 label 控件中:
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 确实存在。否则,您将得到一个system.nullreferenceexception(英文)异常。还需要注意的是,在页面中显示 cookie 的内容之前,我调用了 httpserverutility.htmlencode(英文)方法对cookie 的内容进行编码。之所以这样做,是因为我要显示 cookie 的内容(一般您不会这样做)而且要确保没有任何恶意用户在 cookie 中添加了可执行脚本。有关 cookie
安全性的详细信息,请参阅 cookie 和安全性。
注意:由于不同的浏览器保存 cookie 的方式也不同,所以同一台计算机上的不同浏览器不一定能够相互读取各自的 cookie。例如,如果使用 inte.net explorer 测试一个页面,然后再使用其他浏览器进行测试,那么后者就不会找到 inte.net 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
在上面的示例中,我获取的是子键“lastvist”的值,在此前的讨论中我把该值设置为 datetime 值的字符串表示形式。请记住,cookie 是用字符串的形式保存值的,所以要将 lastvisit 值用作日期,就必须对其进行转换:
dim dt as datetime
dt = cdate(request.cookies("userinfo")("lastvisit"))
cookie 中子键的类型是 namevaluecollection(英文)类型的集合。因此,另一种获取单个子键的方法是先获取子键集合,然后按名称提取子键的值,如下所示:
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
就像设置 cookie 一样,使用哪种方法读取 cookie 也由您自己决定。
什么是有效期?
您可以读取 cookie 的名称和值,除此以外,需要了解的有关 cookie 的信息并不是很多。虽然您可以获取 domain 和 path 属性,但是这些属性的用途很有限。例如,您可以读取 domain 属性,但如果您的页面与 cookie 不在相同的域,您根本就不会在页面的位置接收到该 cookie。
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器