当前位置: 首页 > 图文教程 > 网络编程 > ASP > 尝尝ASP.NET中的小甜饼

ASP
Access 2000 数据库 80 万记录通用快速分页类
Microsoft JET Database Engine 错误 ''80004005'' 未指定的错误的完美解决方法
收藏的ASP常用的函数集
asp分页的一个类
ASP开发网页牢记注意事项
ASP下操作Excel技术总结分析
ASP数据岛操作类
ASP经典分页类
asp论坛在线人数统计研究
ASP调用SQL SERVER存储程序
asp输出bmp
ASP连接数据库的全能代码
ASP面向对象编程探讨及比较
web文件管理器的后续开发
一小偷类!!有兴趣的可以看看
利用ASP实现事务处理的方法
大数量查询分页显示 微软的解决办法
如何把ASP编写成DLL
asp实现树型结构
超级ASP大分页_我的类容我做主

尝尝ASP.NET中的小甜饼


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-11-03   浏览: 195 ::
收藏到网摘: n/a

       Cookie对于使用过ASP的读者来讲并不陌生,但是我们要讲的是在ASP.NET中的Cookie。我们知道,Cookie存在于用户计算机浏览器中,我们可以使用Cookie来存放一些很简单的数据。但是,有一点别说我没提醒你:记住这不是个好办法,因为用户可以在任何时间删除Cookie信息,也可以关闭Cookie功能。好了,开场白就这些。
  
  使用ASP.NET我们可以很容易的对Cookie集合进行操作。它和ASP中的Cookie一样,都是附属于Request和Response对象的。Listing1和2分别给出了如何读和写Cookie的方法。图1和2则是相应的显示。
  Listing 1这个文件的功能是写入cookie
  <%@ language="C#" %>
  <HTML>
   <script language="C#" runat="server">
   void WriteClicked(Object Sender, EventArgs e)
   {
   //创建一个新Cookie,其cookie名来自于NameField.Text
   HttpCookie cookie = new HttpCookie(NameField.Text);
  
   //设定Cookie的值
   cookie.Value = ValueField.Text;
  
   //设定cookie生命为1 minute,TimeSpan()是一个专门设定时间间隔的类,我们定义了其实例tsMinute
   DateTime dtNow = DateTime.Now;
   TimeSpan tsMinute = new TimeSpan(0, 0, 1, 0);
   cookie.Expires = dtNow + tsMinute;
  
   //添加Cookie
   Response.Cookies.Add(cookie);
  
   Response.Write("Cookie written. <br><hr>");
   }
   </script>
   <body>
   <h3>
   Use the button below to write cookies to your browser
   </h3>
   The cookies will expire in one minute.
   <form runat="server" ID="Form1">
   Cookie Name
   <asp:textbox id="NameField" runat="server" />
   <br>
   Cookie Value
   <asp:textbox id="ValueField" runat="server" />
   <br>
   <asp:button text="WriteCookie" onclick="WriteClicked" runat="server" ID="Button1" />
   <br>
   </form>
   <a href="readcookies.aspx">Read the cookies</a>
   </body>
  </HTML>
  图1
   Listing 2 这个文件是为了读取刚才写入的cookie值
  <%@ language="C#" %>
  <script runat="server">
   void ReadClicked(Object Sender, EventArgs e)
   {
   //取得想要的Cookie名
   String strCookieName = NameField.Text;
  
   //取得此Cookie名对应的对象,注意目前的得到的cookie是个对象
   HttpCookie cookie = Request.Cookies[strCookieName];
  
   //检验Cookie是否已经存在
   if (null == cookie) {
   Response.Write("Cookie not found. <br><hr>");
   }
   else {
   //显示Cookie的值
   String strCookieValue = cookie.Value.ToString();
   Response.Write("The " + strCookieName + " cookie contains: <b>"
   + strCookieValue + "</b><br><hr>");
   }
   }
   </script>
  <html>
   <body>
   Use the button below to read a cookie
   <br>
   <form runat="server" ID="Form1">
   Cookie Name
   <asp:textbox id="NameField" runat="server" />
   <asp:button text="ReadCookie" onclick="ReadClicked" runat="server" ID="Button1" />
   </form>
   <a href="writecookies.aspx">Write Cookies</a>
   </body>
  </html>
  
  图2
  为了更好的了解cookie的读写,代