Cookie
Cookie 提供了一种在 Web 应用程序中存储用户特定信息的方法。例如,当用户访问您的站点时,您可以使用 Cookie 存储用户首选项或其他信息。当该用户再次访问您的网站时,应用程序便可以检索以前存储的信息。所以Cookie也可以在页面间传递值。Cookie通过HTTP头在浏览器和服务器之间来回传递的。Cookie只能包含字符串的值,如果想在Cookie存储整数值,那么需要先转换为字符串的形式。
与Session一样,其是什对每一个用户而言的,但是有个本质的区别,即Cookie是存放在客户端的,而session是存放在服务器端的。而且Cookie的使用要配合ASP.NET内置对象Request来使用。
优点:1.使用简单,是保持用户状态的一种非常常用的方法。比如在购物网站中用户跨多个页面表单时可以用它来保持用户状态。
缺点:1.常常被人认为用来收集用户隐私而遭到批评。
2.安全性不高,容易伪造。
例子:(1)a.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="a.aspx.cs" Inherits="WebApplication.a" %><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> ???<title></title></head><body> ???<form id="form1" runat="server"> ???????<div> ???????????<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> ???????????<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /> ???????</div> ???</form></body></html>
(2)a.aspx.cs
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;namespace WebApplication{ ???public partial class a : System.Web.UI.Page ???{ ???????protected void Page_Load(object sender, EventArgs e) ???????{ ???????} ???????protected void Button1_Click(object sender, EventArgs e) ???????{ ???????????var aa = TextBox1.Text.Trim(); ???????????var cookie = new HttpCookie("UserName", aa); ???????????cookie.Expires = DateTime.Now.AddMinutes(1);//设置cookies的作用时间是一分钟 ???????????Response.Cookies.Add(cookie); ???????????Response.Redirect("b.aspx");//跳转到b页面 ???????} ???}}
(3)b.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="b.aspx.cs" Inherits="WebApplication.b" %><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> ???<title></title></head><body> ???<form id="form1" runat="server"> ???????<div> ???????????<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> ???????</div> ???</form></body></html>
(4)b.aspx.cs
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;namespace WebApplication{ ???public partial class b : System.Web.UI.Page ???{ ???????protected void Page_Load(object sender, EventArgs e) ???????{ ???????????Label1.Text = Request.Cookies["UserName"] != null ? Request.Cookies["UserName"].Value : "Cookies值已经失效"; ???????????//三元表达式,等同于下面注释的代码 ???????????//if (Request.Cookies["UserName"] != null) ???????????//{ ???????????// ???Label1.Text = Request.Cookies["UserName"].Value; ???????????//} ???????????//else ???????????//{ ???????????// ???Label1.Text = "Cookies值已经失效"; ???????????//} ???????} ???}}
ps:此文章是本人参考网上内容加上自己的理解整合而成,如无意中侵犯了您的权益,请与本人联系。
ASP.NET页面之间传值的方式之Cookie(个人整理)
原文地址:http://www.cnblogs.com/kudsu/p/7710867.html