代码语言
.
CSharp
.
JS
Java
Asp.Net
C
MSSQL
PHP
Css
PLSQL
Python
Shell
EBS
ASP
Perl
ObjC
VB.Net
VBS
MYSQL
GO
Delphi
AS
DB2
Domino
Rails
ActionScript
Scala
代码分类
文件
系统
字符串
数据库
网络相关
图形/GUI
多媒体
算法
游戏
Jquery
Extjs
Android
HTML5
菜单
网页交互
WinForm
控件
企业应用
安全与加密
脚本/批处理
开放平台
其它
【
Asp.Net
】
Cookie存、取,使用方法实例
作者:
Dezai.CN
/ 发布于
2013/3/7
/
732
Cookie存、取,使用方法实例
1,CookiesWriter 页面,实现点击按钮存cookie ; using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; public partial class _20110328Cookies_CookiesWriter : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } public void setCookiesForUser() { HttpCookie cookie = new HttpCookie("XXH_CookiesInfo"); cookie.Values.Add("xxh", this.txtCookies.Text.Trim() + System.DateTime.Now.ToString()); cookie.Expires = System.DateTime.Now.AddDays(1); //设置Cookies失效时间 Response.Cookies.Add(cookie); } protected void btnAddCookies_Click(object sender, EventArgs e) { setCookiesForUser(); Response.Redirect("CookiesReader.aspx"); } } 2,CookiesReader页面,实现读取cookie ; using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; public partial class _20110328Cookies_CookiesReader : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!this.Page.IsPostBack) { getCookies(); } } public void getCookies() { HttpCookie cookie = Request.Cookies["XXH_CookiesInfo"]; if (cookie == null) { return; } else { if (cookie.Values.Count > 0) { string userInfo = cookie.Values["xxh"]; Response.Write(userInfo); //遍历每一个Cookies值 Response.Write("下面是遍历Cookies里的每一个值:"); string[] sArray = userInfo.Split(','); foreach (string i in sArray) { Response.Write(i.ToString() + ""); } } else { Response.Write(cookie.Name+"Cookies记录为空值"); } } } } 3,CookiesWriter3存储同名连续的cookie 值 using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Data.SqlClient; public partial class _20110328Cookies_CookiesWriter3 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!this.Page.IsPostBack) { ddlUsersListDataBind(); } } public void ddlUsersListDataBind() { string connection = ConfigurationManager.ConnectionStrings["connectionXXH_LogManager"].ConnectionString; string sql = "SELECT * FROM UsersInfo"; SqlConnection con = new SqlConnection(connection); SqlDataAdapter sda = new SqlDataAdapter(sql, con); DataSet ds = new DataSet(); sda.Fill(ds); ddlUsersList.DataSource = ds; ddlUsersList.DataTextField = "UserName"; ddlUsersList.DataValueField = "UserID"; ddlUsersList.DataBind(); } protected void ddlUsersList_SelectedIndexChanged(object sender, EventArgs e) { setCookiesForUsers(); } public void setCookiesForUsers() //获取原有的Cookies记录内容 { HttpCookie cookies = Request.Cookies["XXH_CookiesUserInfo"]; if (cookies == null) // || cookies.Values.Count == 0 { cookies = new HttpCookie("XXH_CookiesUserInfo"); cookies.Values.Add("user", ddlUsersList.SelectedValue); cookies.Expires = System.DateTime.MaxValue; //设置Cookies失效时间 Response.Cookies.Add(cookies); Response.Write("<script language='javascript' defer>alert('首次添加" + ddlUsersList.SelectedItem.Value + "到Cookies成功');</script>"); } else { if (cookies.Values["user"] != "") { string cookPre = Convert.ToString(cookies.Values["user"]); cookies.Values.Set("user", (cookPre + "," + ddlUsersList.SelectedValue)); //修改cookies.Values["user"]值 cookies.Expires = System.DateTime.MaxValue; //设置Cookies失效时间 Response.AppendCookie(cookies); Response.Write("<script language='javascript' defer>alert('自动添加" + ddlUsersList.SelectedItem.Value + "到Cookies成功');</script>"); } } } } 4,读取连续的cookie 值,并根据id显示相关内容 using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Data.SqlClient; public partial class _20110328Cookies_CookiesReaderByID : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!this.Page.IsPostBack) { getCookies(); } } public void getCookies() { HttpCookie cookie = Request.Cookies["XXH_CookiesUserInfo"]; if (cookie == null) { return; } else { if (cookie.Values.Count > 0) { string userInfo = cookie.Values["user"]; Response.Write(userInfo); //遍历每一个Cookies值 Response.Write("下面是遍历Cookies里的每一个值:"); string[] sArray = userInfo.Split(','); foreach (string i in sArray) { Response.Write(i.ToString() + ""); getUserInfoByID(Convert.ToInt32(i)); } } else { Response.Write(cookie.Name + "Cookies记录为空值"); } } } public void getUserInfoByID(int ID) { string connection = ConfigurationManager.ConnectionStrings["connectionXXH_LogManager"].ConnectionString; string sql = "SELECT * FROM UsersInfo WHERE UserID=" + ID + ""; SqlConnection con = new SqlConnection(connection); SqlDataAdapter sda = new SqlDataAdapter(sql, con); DataSet ds = new DataSet(); sda.Fill(ds); if (ds.Tables[0].Rows.Count > 0) { Response.Write("用户信息:ID=" + ID + "用户名=" + Convert.ToString(ds.Tables[0].Rows[0]["UserName"]) + "生日=" + Convert.ToString(ds.Tables[0].Rows[0]["Birthday"]) + ""); } else { Response.Write("<script language='javascript' defer>alert('没有找到用户信息!');</script>"); } } } 5,用JS存Cookies练习实例 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="CookiesWriterJS.aspx.cs" Inherits="_20110328Cookies_CookiesWriterJS" %> <!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>用JS存Cookies练习</title> <script type="text/javascript" language="javascript"> //添加cookie function addCookie(objName,objValue,objHours){//debugger; var str = objName + "=" + escape(objValue); //为0时不设定过期时间,浏览器关闭时cookie自动消失 if(objHours > 0){ var date = new Date(); var ms = objHours*3600*1000; date.setTime(date.getTime() + ms); str += "; expires=" + date.toGMTString(); } document.cookie = str; alert("添加cookie成功"); } //获取指定名称的cookie的值 function getCookie(objName){//debugger; var arrStr = document.cookie.split("; "); for(var i = 0;i < arrStr.length;i ++){ var temp = arrStr[i].split("="); if(temp[0] == objName) { return unescape(temp[1]);//返回一个包含charstring内容的字符串值 } } } //为了删除指定名称的cookie,可以将其过期时间设定为一个过去的时间 function delCookie(objName){//debugger; var date = new Date(); date.setTime(date.getTime() - 10000); document.cookie = objName + "=a; expires=" + date.toGMTString(); } //读取所有保存的cookie字符串 function allCookie(){ var str = document.cookie; if(str == ""){ str = "没有保存任何cookie"; } alert(str); } //找文档表单m内部控件n function $(m,n){//debugger; return document.forms[m].elements[n].value; } function add_(){ var cookie_name = $("myform","cookie_name"); var cookie_value = $("myform","cookie_value"); var cookie_expireHours = $("myform","cookie_expiresHours"); addCookie(cookie_name,cookie_value,cookie_expireHours); } function get_(){ var cookie_name = $("myform","cookie_name"); var cookie_value = getCookie(cookie_name); alert(cookie_value); } function del_(){ var cookie_name = $("myform","cookie_name"); delCookie(cookie_name); alert("删除成功"); } </script> </head> <body> <form name="myform" runat="server"> <div><label for="cookie_name">名称</label><input type="text" name="cookie_name" /></div> <div><label for="cookie_value">值</label><input type="text" name="cookie_value" /></div> <div><label for="cookie_expireHours">多少个小时过期</label><input type="text" name="cookie_expiresHours" /></div> <div> <input type="button" value="添加该cookie" onclick="add_()" /> <input type="button" value="读取所有cookie" onclick="allCookie()" /> <input type="button" value="读取该名称cookie" onclick="get_()" /> <input type="button" value="删除该名称cookie" onclick="del_()" /> </div> </form> </body> </html>
试试其它关键字
Cookie
同语言下
.
gzip压缩
.
实现http多线程断点续传下载文件
.
实现多线程断点续传下载大文件
.
生成字符串的 CheckSum
.
根据 UserAgent 获取浏览器的类型和版本
.
根据 Agent 判断是否是智能手机
.
隐藏手机号中间四位为*方法
.
合并图片(二维码和其他图片合并)
.
ASP.NET CORE中判断是否移动端打开网页
.
ASP.NET(C#)实现页面计时(定时)自动跳转
可能有用的
.
C#实现的html内容截取
.
List 切割成几份 工具类
.
SQL查询 多列合并成一行用逗号隔开
.
一行一行读取txt的内容
.
C#动态修改文件夹名称(FSO实现,不移动文件)
.
c# 移动文件或文件夹
.
c#图片添加水印
.
Java PDF转换成图片并输出给前台展示
.
网站后台修改图片尺寸代码
.
处理大图片在缩略图时的展示
Dezai.CN
贡献的其它代码
(
4037
)
.
多线程Socket服务器模块
.
生成随机密码
.
清除浮动样式
.
弹出窗口居中
.
抓取url的函数
.
使用base HTTP验证
.
div模拟iframe嵌入效果
.
通过header转向的方法
.
Session操作类
.
执行sqlite输入插入操作后获得自动编号的ID
Copyright © 2004 - 2024 dezai.cn. All Rights Reserved
站长博客
粤ICP备13059550号-3