8、使用浏览器Cookie

使用浏览器Cookie

set-cookie:message=hello

注意:
Cookie就是一段文本。Cookie只能用于存储字符串值。

可以创建两种类型的cookie:会话Cookie和持久化Cookie
会话Cookie只存于内存,当用户关闭浏览器时,会话Cookie就永远消失了。
持久化Cookie可以存在几个月甚至几年。持久化Cookie创建后,会被浏览器长久地保存在用户的电脑上。
\Documents and Settings\[user]\Cookies


1、Cookie的安全性限制
首先,所有的Cookie是与域名相关的
其次,浏览器存储Cookie的重要限制是其大小的限制 不能超过4096字节(包含所有的Cookie名称和值在内)
最后,大多数浏览器都限制可以被设置的cookie数量,一个域名不超过20个cookie (IE除外)

2、创建Cookie
Response.Cookies 集合添加Cookie
[code]
<%@ 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></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblCookieValue" runat="server" AssociatedControlID="txtCookieValue"
Text="Cookie Value"></asp:Label>
<asp:TextBox ID="txtCookieValue" runat="server"></asp:TextBox>
<asp:Button ID="btnAdd" runat="server" Text="Add Value" OnClick="btnAdd_Click" />
</div>
</form>
</body>
</html>
[/code]
Cookie的名称是区分大小写的。
2011-5-11 11:48 danny

创建持久化的Cookie
[code]
<%@ 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 Page_Load(object sender, EventArgs e)
{
int counter = 0;
if (Request.Cookies["counter"] != null)
counter = Int32.Parse(Request.Cookies["counter"].Value);
counter++;
Response.Cookies["counter"].Value = counter.ToString();
Response.Cookies["counter"].Expires = DateTime.Now.AddYears(2);
lblCounter.Text = counter.ToString();
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
You have visited this page
<asp:Label ID="lblCounter" runat="server" Text="Label"></asp:Label>
times!
</div>
</form>
</body>
</html>
[/code]
Response.Cookies["counter"].Expires = DateTime.Now.AddYears(2);
设为两年。当为某个Cookie设置了过期时间后,该Cookie就被保存为持久化cookie了。

3、读取Cookie
可以使用Response.Cookies集合创建和修改Cookie,
可以使用Request.Cookies集合读取Cookie值

GetCookies.aspx
[code]
<%@ 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 Page_Load(object sender, EventArgs e)
{
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></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="grdCookies" runat="server">
</asp:GridView>
</div>
</form>
</body>
</html>

[/code]

4、设置Cookie属性
Domain 关联到的Cookie的域名。默认当前域名
Expires 指定过期时间
HasKeys 确定该Cookie是否是一个多值cookie
HttpOnly 避免Cookie被JavaScript访问
Name 用户指定Cookie的名称
Path 关联到Cookie的路径。默认值是/
Secure 指定Cookie需要通过SSL连接传递
Value 允许读/写Cookie的值
Values 多值

5、删除Cookie
删除Cookie的方法并不直观。要删除一个存在的Cookie,必须设置其过期时间为一个过去的时间。

DeleteAllCookies.aspx
[code]
<%@ 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 Page_Load(object sender, EventArgs e)
{
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 runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:BulletedList ID="BulletedList1" EnableViewState="false" runat="server">
</asp:BulletedList>
</div>
</form>
</body>
</html>
[/code]

<%@ 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 Page_Load(object sender, EventArgs e)
{
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 runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:BulletedList ID="BulletedList1" EnableViewState="false" runat="server">
</asp:BulletedList>
</div>
</form>
</body>
</html>

2011-5-11 22:20 danny
6、使用多值Cookie
根据Cookie规范,单个域名,浏览器不能存储超过20个Cookie。可以通过创建多值Cookie来超越该限制。
多值Cookie是一个包含子键的Cookie。可以根据需要创建任意数量的子键。

setCookieValues.aspx
[code]
<%@ 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 btnSubmit_Click(object sender, EventArgs e)
{
Response.Cookies["preferences"]["firstName"] = TxtFirstName.Text;
Response.Cookies["preferences"]["lastName"] = txtLastName.Text;
Response.Cookies["preferences"]["favoriteColor"] = txtFavoriteColor.Text;
Response.Cookies["preferences"].Expires = DateTime.MaxValue;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblFirstName" runat="server" AssociatedControlID="TxtFirstName" Text="First Name"></asp:Label>
<br />
<asp:TextBox ID="TxtFirstName" runat="server"></asp:TextBox>
<br />
<asp:Label ID="lblLastName" runat="server" AssociatedControlID="TxtFirstName" Text="Last Name"></asp:Label>
<br />
<asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
<br />
<asp:Label ID="lblFavoriteColor" runat="server" AssociatedControlID="TxtFirstName"
Text="Favorite Color"></asp:Label>
<br />
<asp:TextBox ID="txtFavoriteColor" runat="server"></asp:TextBox>
<br />
<asp:Button ID="btnSubmit" Text="Submit" runat="server" OnClick="btnSubmit_Click" />
</div>
</form>
</body>
</html>
[/code]

查看
GetCookieValues.aspx
[code]
<%@ 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 Page_Load(object sender, EventArgs e)
{
if (Request.Cookies["preferences"] != null)
{
lblFirstName.Text = Request.Cookies["preferences"]["firstName"];
lblLastName.Text = Request.Cookies["preferences"]["lastName"];
lblFavoriteColor.Text = Request.Cookies["preferences"]["favoriteColor"];
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
First Name:
<asp:Label ID="lblFirstName" runat="server"></asp:Label>
<br />
Last Name:
<asp:Label ID="lblLastName" runat="server"></asp:Label>
<br />
Favorite Color:
<asp:Label ID="lblFavoriteColor" runat="server"></asp:Label>
<br />
</div>
</form>
</body>
</html>
[/code]

2011-5-13 10:59 danny
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
特别说明请注意: 根许多网友反应, using Maticsoft.Functions; 这些代码看不懂 其实Functions 这个dll是我定义常用的函数类,如果需要跟我联系索取http://sql8.net 下面有我的群号, 其中 ArtsShop.Model.Arts_Product _p = new ArtsShop.Model.Arts_Product(); ArtsShop.BLL.Arts_Product p = new ArtsShop.BLL.Arts_Product(); _p = p.GetModel(id); 这是我的商品信息的类,三层结构,这个在用时你们只能换成你们自己的,这些代码完全可以删除, 比如 MyDr[1] = _p.Title; 用来取商品名的,你们可以改MyDr[1] = dr["productname"].ToString();就行了, AddToCart.aspx页面代码 无标题页 <asp:TextBox ID="TextBox1" runat="server" Text='' Width="44px"> <asp:Label ID="Label1" runat="server" Text=''> 保存 取消 编辑 继续购物 清空购物车 下订单 AddToCart.aspx.cs页面代码 using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using Maticsoft.Functions;public partial class AddToCart : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { int ProID; HttpCookie cookie; bool Tempbl = false; string Tempstr; if (!Page.IsPostBack) { if (!object.Equals(Request.QueryString["id"], null)) { ProID = int.Parse(Request.QueryString["id"]); //创购物车cookie yxy .//sql8.net if (object.Equals(Request.Cookies["ztbscart"], null)) cookie = new HttpCookie("ztbscart"); else cookie = Request.Cookies["ztbscart"]; //判断是否已存在于购物车内 yxy // sql8.net for (int i = 0; i < cookie.Values.Keys.Count; i++) { if (!object.Equals(cookie.Values.Keys[i], null)) { Tempstr = cookie.Values.AllKeys[i].ToString(); if (Tempstr.Trim() != "") { if (ProID == int.Parse(cookie.Values.AllKeys[i])) { Tempbl = true; break; } } } } //不未购买过则加入购物车 yxy //sql8.net if (!Tempbl) cookie.Values.Add(ProID.ToString(), "1"); else { } TimeSpan ts = new TimeSpan(0, 0, 10, 0); cookie.Expires = DateTime.Now + ts; Response.AppendCookie(cookie); } BindGrid(); } } //绑定数据 yxy //sql8.net private void BindGrid() { DataTable MyDt; DataRow MyDr; string str = ""; MyDt = new DataTable(); MyDt.Columns.Add(new DataColumn("id", str.GetType())); MyDt.Columns.Add(new DataColumn("Title", str.GetType())); MyDt.Columns.Add(new DataColumn("Num", str.GetType())); MyDt.Columns.Add(new DataColumn("Price", str.GetType())); MyDt.Columns.Add(new DataColumn("Discount", str.GetType())); MyDt.Columns.Add(new DataColumn("Vipprice", str.GetType())); MyDt.Columns.Add(new DataColumn("Totle", str.GetType())); if (!object.Equals(Request.Cookies["ztbscart"], null)) { HttpCookie cookie = Request.Cookies["ztbscart"]; double Totle; //Response.Write("|" + Request.Cookies["ztbscart"].Values.Keys[1].ToString() + "|"); //Response.End(); for (int i = 0; i < cookie.Values.Keys.Count; i++) { int id; MyDr = MyDt.NewRow(); if (cookie.Values.AllKeys[i] != "" && cookie.Values[i] != "") { id = int.Parse(cookie.Values.AllKeys[i].ToString()); ArtsShop.Model.Arts_Product _p = new ArtsShop.Model.Arts_Product(); ArtsShop.BLL.Arts_Product p = new ArtsShop.BLL.Arts_Product(); _p = p.GetModel(id); MyDr[0] = id; MyDr[1] = _p.Title; MyDr[2] = cookie.Values[i]; MyDr[3] = _p.Price; MyDr[4] = _p.Discount; MyDr[5] = _p.Vipprice1; Totle = double.Parse(MyDr[2].ToString()) * double.Parse(MyDr[5].ToString()); MyDr[6] = Totle; MyDt.Rows.Add(MyDr); } } GridView1.DataSource = MyDt.DefaultView; GridView1.DataBind(); } } protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { //编辑某行数量 yxy //sql8.net GridView1.EditIndex = e.NewEditIndex; BindGrid(); } protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { //取消更新 yxy //sql8.net GridView1.EditIndex = -1; BindGrid(); } protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { //更新数量 yxy //sql8.net string num; TextBox tempbx = new TextBox(); Label templb = new Label(); tempbx = (TextBox)(GridView1.Rows[e.RowIndex].Cells[6]).Controls[1]; num = tempbx.Text.ToString(); HttpCookie cookie = new HttpCookie("ztbscart"); for (int i = 0; i < GridView1.Rows.Count; i++) { string id; string tempnum; id = GridView1.Rows[i].Cells[1].Text.ToString(); if (e.RowIndex == i) tempnum = num; else { templb = (Label)(GridView1.Rows[i].Cells[6]).Controls[1]; tempnum = templb.Text.ToString(); } if (tempnum.Trim() == "") tempnum = "0"; //Response.Write("ID:"+id.ToString() + "Num:"+tempnum+":"+i+"");//测试用途 yxy//sql8.net cookie.Values.Add(id, tempnum); } //Response.End(); TimeSpan ts = new TimeSpan(0, 0, 10, 0); cookie.Expires = DateTime.Now + ts; Response.AppendCookie(cookie); GridView1.EditIndex = -1; Message.GoTo("AddToCart.aspx"); } protected void LinkButton4_Click(object sender, EventArgs e) { //继续购物 yxy //sql8.net Message.WebClose(); } protected void LinkButton3_Click(object sender, EventArgs e) { //清空购物车 yxy //sql8.net CheckBox tempcb = new CheckBox(); HttpCookie cookie = new HttpCookie("ztbscart"); Label templb = new Label(); for (int i = 0; i < GridView1.Rows.Count; i++) { tempcb = (CheckBox)(GridView1.Rows[i].Cells[0]).Controls[1]; if (!tempcb.Checked) { string id; string tempnum; id = GridView1.Rows[i].Cells[1].Text.ToString(); templb = (Label)(GridView1.Rows[i].Cells[6]).Controls[1]; tempnum = templb.Text.ToString(); if (tempnum.Trim() == "") tempnum = "0"; //Response.Write("ID:"+id.ToString() + "Num:"+tempnum+":"+i+"");//测试用途 yxy//sql8.net cookie.Values.Add(id, tempnum); } } TimeSpan ts = new TimeSpan(0, 0, 10, 0); cookie.Expires = DateTime.Now + ts; Response.AppendCookie(cookie); Message.GoTo("AddToCart.aspx"); } protected void CheckAll_CheckedChanged(object sender, EventArgs e) { //全选事件 yxy //sql8.net CheckBox tempcb = new CheckBox(); bool tempbl; tempcb = (CheckBox)(GridView1.HeaderRow.Cells[0]).Controls[1]; tempbl = tempcb.Checked; for (int i = 0; i < GridView1.Rows.Count; i++) { tempcb = (CheckBox)(GridView1.Rows[i].Cells[0]).Controls[1]; tempcb.Checked = tempbl; } } } _________________________________________________________________________ 如转载请注明原出处 www.sql8.net
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值