6. Asp.net 中的Cookie
Cookie是记录客户端的一些信息,是用户要求记录的。但它是和服务端相连的,向服务器请求的时候除了发送表单参数外还会把与站点相关的所有Cookie提交给服务器,这是强制性的,服务器会把修改后的cookie值返回给浏览器并更新本地的cookie。
cookie也是键/值对,以下为读写的操作。
在asp.net 中设置cookie的操作为(写):
Response.SetCookie(new HttpCookie(key,value));
读的操作为:
Request.Cookies[key].Value;
即写的操作是由响应操作的,即Response,读的操作是浏览器请求得到的,即Request.
cookie也是不能存储过多信息,它为object类型。以下为读写操作:
1.设置cookie
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="setcookie1.aspx.cs" Inherits="setcookie1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="设置cookie" /> </div> </form> </body> </html>
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class setcookie1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { //设置cookie用respone,即服务端向客户端写入信息 Response.SetCookie(new HttpCookie("cookiekey",TextBox1.Text)); Response.Redirect("readcookie1.aspx"); }
2.读cookie
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="readcookie1.aspx.cs" Inherits="readcookie1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="得到cookie" /> <asp:Label ID="Label1" runat="server"></asp:Label> </div> </form> </body> </html>
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; public partial class readcookie1 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { Label1.Text = Request.Cookies["cookiekey"].Value; } }
cookie只与它的域名有关,相同的域名在不同的浏览器中会产生不同的cookie.