在各个网页间的变量传递和一些记录用户的登陆信息要用到SESSION和COOKIE。在ASP.NET中使用COOKIE比ASP中稍微麻烦一点,因为我们要申明变量。
首先看一下SESSION的使用,基本和ASP差不多
写入一个SESSION:
读取一个SESSINN:
-------------------------
再来看一下COOKIE的写入:
写入一个SESSION:
Session["username"])="aa";
Session("username")="aa"
读取一个SESSINN:
string username= Session["username"];
-------------------------
再来看一下COOKIE的写入:
DateTime dt=DateTime.Now; //需要<%@Import Namespace="System"%>,得到当前时间
HttpCookie mycookie=new HttpCookie("logname");//申明新的COOKIE变量
mycookie.Value="aa";//赋值
mycookie.Expires=Convert.ToDateTime(dt+TimeSpan.FromDays(1));//设定过期时间为1天
Response.Cookies.Add(mycookie1);//写入COOKIE
dt=DataTime.Now
dim mycookie as HttpCookie
mycookie=new HttpCookie("logname")
mycookie.Value="aa"
mycookie.Expires=Convert.ToDateTime(dt+TimeSpan.FromDays(1))
Response.Cookies.Add(mycookie1)
看一下COOKIE的读取:
HttpCookie mycookie=Request.Cookies["username"];
string username=mycookie.Value;
-----------------------
dim mycookie as HttpCookie
mycookie=Request.Cookies["username"]
dim string=mycookie.Value
下面是js操作cookies的方法
//设置cookies
function setCookie(name, value) {
var days = 1; //此cookie将被保存1天
var exp = new Date();
exp.setTime(exp.getTime() + days * 24 * 60 * 60 * 1000);
document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
}
//删除cookies
function delCookie(name) {
var exp = new Date();
exp.setTime(exp.getTime() - 1);
document.cookie = name + "=;expires=" + exp.toGMTString();
}
//读取cookies
function ReadCookie(name) {
var acookie = document.cookie.split(';');
for (var i = 0; i < acookie.length; i++) {
var arr = acookie[i].split('=');
if (name == arr[0]) {
if (arr.length > 1)
return unescape(arr[1]);
else
return "";
}
}
return "";
}