当前位置:编程学习 > C#/ASP.NET >>

asp.net cookie值获取 删除 显示代码

asp教程.net cookie值获取  删除 显示代码
cookie 是一小段文本信息,伴随着用户请求和页面在 web 服务器和浏览器之间传

递。cookie 包含每次用户访问站点时 web 应用程序都可以读取的信息。

例如,如果在用户请求站点中的页面时应用程序发送给该用户的不仅仅是一个页面

,还有一个包含日期和时间的 cookie,用户的浏览器在获得页面的同时还获得了

该 cookie,并将它存储在用户硬盘上的某个文件夹中。

 

设置cookie

<%@ page language="vb" %>
<html>
   <head>
      <title>setting a cookie in asp.net教程</title>
      <script runat="server">
         sub page_load()
            dim mycookie as new httpcookie("loggedin")
            mycookie.value = "true"
            mycookie.expires = datetime.now.addminutes(30)
            response.cookies.add(mycookie)
         end sub
      </script>
   </head>
<body>
   <asp:label id="message" runat="server"/>
</body>
</html>

显示所有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 id="head1" 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>

删除所有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()
    {
        string[] cookies = request.cookies.allkeys;
        foreach (string cookie in cookies)
        {
            bulletedlist1.items.add("deleting " + cookie);
            response.cookies[cookie].expires = datetime.now.adddays(-1);
        }
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="head1" runat="server">
    <title>delete all cookies</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
   
    <h1>delete all cookies</h1>
   
    <asp:bulletedlist
        id="bulletedlist1"
        enableviewstate="false"
        runat="server" />
   
    </div>
    </form>
</body>
</html>


如果没有设置 cookie 的有效期,仍会创建 cookie,但不会将其存储在用户的硬

盘上。而会将 cookie 作为用户会话信息的一部分进行维护。当用户关闭浏览器时

,cookie 便会被丢弃。这种非永久性 cookie 很适合用来保存只需短时间存储的

信息,或者保存由于安全原因不应该写入客户端计算机上的磁盘的信息。例如,如

果用户在使用一台公用计算机,而您不希望将 cookie 写入该计算机的磁盘中,这

时就可以使用非永久性 cookie。

补充:asp.net教程,基础入门 
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,