asp.net学会SESSION和COOKIE的使用(C# | VB)
在各个网页间的变量传递和一些记录用户的登陆信息要用到SESSION和COOKIE。在ASP.NET中使用COOKIE比ASP中稍微麻烦一点,因为我们要申明变量。
首先看一下SESSION的使用,基本和ASP差不多
写入一个SESSION:
Session["username"]="aa";
---------------------
Session("username")="aa"
读取一个SESSINN:
string username= Session["username"];
-------------------------
dim 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
-------------------------------
dim dt as DateTime
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