网摘 |  收藏 | 

读取cookie

《ASP.NET 3.5 揭秘》

使用Request.Cookies集合可以读取cookie值

View Code
 1 <%@ Page Language="C#" %>
 2 
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4 
 5 <script runat="server">
 6     void Page_Load()
 7     {
 8         if (Request.Cookies["message"] != null)
 9         {
10             lblCookieValue.Text = Request.Cookies["message"].Value; 
11         } 
12     }
13 </script>
14 
15 <html xmlns="http://www.w3.org/1999/xhtml">
16 <head runat="server">
17     <title>Get Cookie</title>
18 </head>
19 <body>
20     <form id="form1" runat="server">
21     <div>
22     
23     The value of the message cookie is:
24     <asp:Label
25         id="lblCookieValue"
26         Runat = "server" />
27     </div>
28     </form>
29 </body>
30 </html>


如果想读出Request.Cookies集合中所有的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">
    void Page_Load()
    {
        ArrayList colCookies = new ArrayList();
        for (int i = 0; i < Request.Cookies.Count; i++)
        {
            colCookies.Add(Request.Cookies[i]); 
        }

        grdCookies.DataSource = colCookies;
        grdCookies.DataBind();
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Get All Cookies</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    <asp:GridView
        id="grdCookies"
        Runat="server" />
    </div>
    </form>
</body>
</html>

 

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