Cookie常用

jiels - by - 18 六月, 2006 03:40

 

Response.Cookies["userName"].Value = "patrick";
Response.Cookies[
"userName"].Expires = DateTime.Now.AddDays(1);

HttpCookie aCookie 
= new HttpCookie("lastVisit");
aCookie.Value 
= DateTime.Now.ToString();
aCookie.Expires 
= DateTime.Now.AddDays(1);
Response.Cookies.Add(aCookie);

此示例向 Cookies 集合添加两个 Cookie,一个名为 userName,另一个名为 lastVisit。对于第一个 Cookie,Cookies 集合的值是直接设置的。可以通过这种方式向集合添加值,因为 Cookies 是从 NameObjectCollectionBase 类型的专用集合派生的。

对于第二个 Cookie,代码创建了一个 HttpCookie 类型的对象实例,设置其属性,然后通过 Add 方法将其添加到 Cookies 集合。在实例化 HttpCookie 对象时,必须将该 Cookie 的名称作为构造函数的一部分进行传递。

这两个示例都完成了同一任务,即向浏览器写入一个 Cookie。在这两种方法中,有效期值必须为 DateTime 类型。但是,lastVisited 值也是日期时间值。因为所有 Cookie 值都存储为字符串,因此,必须将日期时间值转换为 String。


多值

Response.Cookies["userInfo"]["userName"= "patrick";
Response.Cookies[
"userInfo"]["lastVisit"= DateTime.Now.ToString();
Response.Cookies[
"userInfo"].Expires = DateTime.Now.AddDays(1);

HttpCookie aCookie 
= new HttpCookie("userInfo");
aCookie.Values[
"userName"= "patrick";
aCookie.Values[
"lastVisit"= DateTime.Now.ToString();
aCookie.Expires 
= DateTime.Now.AddDays(1);
Response.Cookies.Add(aCookie);

 

读取 Cookie

浏览器向服务器发出请求时,会随请求一起发送该服务器的 Cookie。在 ASP.NET 应用程序中,可以使用 HttpRequest 对象读取 Cookie,该对象可用作 Page 类的 Request 属性使用。HttpRequest 对象的结构与 HttpResponse 对象的结构基本相同,因此,可以从 HttpRequest 对象中读取 Cookie,并且读取方式与将 Cookie 写入 HttpResponse 对象的方式基本相同。下面的代码示例演示两种方法,通过这两种方法可获取名为 username 的 Cookie 的值,并将其值显示在 Label 控件中:

if(Request.Cookies["userName"!= null)
    Label1.Text 
= Server.HtmlEncode(Request.Cookies["userName"].Value);

if(Request.Cookies["userName"!= null)
{
    HttpCookie aCookie 
= Request.Cookies["userName"];
    Label1.Text 
= Server.HtmlEncode(aCookie.Value);
}


在尝试获取 Cookie 的值之前,应确保该 Cookie 存在;如果该 Cookie 不存在,将会收到 NullReferenceException 异常。还请注意在页面中显示 Cookie 的内容前,先调用 HtmlEncode 方法对 Cookie 的内容进行编码。这样可以确保恶意用户没有向 Cookie 中添加可执行脚本。

读取 Cookie 中子键值的方法与设置该值的方法类似。下面的代码示例演示获取子键值的一种方法:

if(Request.Cookies["userInfo"!= null)
{
    Label1.Text 
= 
        Server.HtmlEncode(Request.Cookies[
"userInfo"]["userName"]);

    Label2.Text 
=
        Server.HtmlEncode(Request.Cookies[
"userInfo"]["lastVisit"]);
}


在上面的示例中,代码读取子键 lastVisit 的值,该值先前被设置为字符串表示形式的 DateTime 值。Cookie 将值存储为字符串,因此,如果要将 lastVisit 值作为日期使用,必须将其转换为适当的类型,如此示例所示:

DateTime dt;
dt 
= DateTime.Parse(Request.Cookies["userInfo"]["lastVisit"]);


Cookie 中的子键被类型化为 NameValueCollection 类型的集合。因此,获取单个子键的另一种方法是获取子键集合,然后再按名称提取子键值,如下面的示例所示:

if(Request.Cookies["userInfo"!= null)
{
    System.Collections.Specialized.NameValueCollection
        UserInfoCookieCollection;
       
    UserInfoCookieCollection 
= Request.Cookies["userInfo"].Values;
    Label1.Text 
= 
        Server.HtmlEncode(UserInfoCookieCollection[
"userName"]);
    Label2.Text 
=
        Server.HtmlEncode(UserInfoCookieCollection[
"lastVisit"]);
}

posted @ 2006-06-20 19:02  James_Chen  阅读(532)  评论(0编辑  收藏  举报