网摘 |  收藏 | 

创建cookie

《ASP.NET 3.5揭秘》读书笔记

cookie 分为:会话cookie和持久化cookie两种。

会话cookie只存在于内存中;

持久化cookie可以存在几个月甚至几年,持久化cookie创建后,会被浏览器长久地保存在用户的电脑上。(如IE存在这个文件夹里:\Documents and Settings\[user]\Cookies)

创建会话cookie。

通过Response.Cookies集合添加cookie来创建新的cookie。

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    protected void btnAdd_Click(object sender, EventArgs e)
    {
        Response.Cookies["message"].Value = txtCookieValue.Text; 
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Set Cookie</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    <asp:Label
        id="lblCookieValue"
        Text="Cookie Value:"
        AssociatedControlID="txtCookieValue"
        Runat="server"/>
    <asp:TextBox
        id="txtCookieValue"
        Runat="server" />
    <asp:Button
        id="btnAdd"
        Text="Add Value"
        OnClick="btnAdd_Click"
        Runat="server"/>
    </div>
    </form>
</body>
</html>

创建持久cookie。

如果希望创建持久化cookies,则需要为cookie指定一个过期时间。如下面程序中Respo.Cookies["counter"].Expires = DataTime.Now.AddYears(2);

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    void Page_Load()
    {
         // Get current value of cookie
        int counter = 0;
        if (Request.Cookies["counter"] != null)
        {
            counter = Int32.Parse(Request.Cookies["counter"].Value);
        }
        
        // Increment counter
        counter++;
        
        // Add Peristent cookie to browser
        Response.Cookies["counter"].Value = counter.ToString();
        Response.Cookies["counter"].Expires = DateTime.Now.AddYears(2);
        
        // Display value of counter cookie
        lblCounter.Text = counter.ToString();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Set Persister Cookie</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    You have visited this page
    <asp:Label
        id="lblCounter"
        Runat = "server" />
    times!
    </div>
    </form>
</body>
</html>

 

posted @ 2012-11-15 14:12  xulonghua219  阅读(1396)  评论(0编辑  收藏  举报