//Application
Application["Name"] = "lisi";
string Result1 = Application["Name"].ToString();
//Session
//优点 使用简单,不仅能传递简单数据类型,还能传递对象.数据量大小是不限制的.存放在服务器端
//缺点 在Session变量存储大量的数据会消耗较多的服务器资源.
Session["name"] = "Value";
string Result2 = Session["name"].ToString();
//清空所有session对象的值,但保留会话
Session.Clear();
//调用clear()方法
Session.RemoveAll();
//删除某个session对象
Session.Remove("name");
//结束当前会话并删除所有session对象,并 调用Session_End方法(InProc模式下)。当下一个请求到来时将激发Session_Start方法。 Abandon方法用于主动结束会话,若没有调用该方法,当会话超时后,也会自动结束当前会话。
Session.Abandon();
//Cookie
//比如我们建立一个名为user的cookie
HttpCookie cookie = new HttpCookie("user");
//赋值为Test
cookie.Value = "Test";
//设置Cookies有效期为1天.默认cookie在浏览器关闭的时候自动失效
cookie.Expires = DateTime.Now.AddDays(1);
//将Cookies存入
Response.AppendCookie(cookie);
//取出Cookie值
HttpCookie cookieOne = Request.Cookies["user"];
string cookieValue = cookieOne.Value;
//一个Cookie中储存多个信息,比如我们在名为user1的cookie下加多个信息
HttpCookie cookieTwo = new HttpCookie("user1");
cookieTwo.Values.Add("name", "222");
cookieTwo.Values.Add("pwd", "333");
cookieTwo.Values.Add("member", "admin");
Response.AppendCookie(cookieTwo);
//从客户端获取取信息也一样简单
HttpCookie cookie3 = Request.Cookies["cookieTwo"];
string value1 = cookie3.Values["name"];
string value2 = cookie3.Values["pwd"];
HttpCookie aCookie = new HttpCookie("userInfo");
aCookie.Values["userName"] = "patrick";
aCookie.Values["lastVisit"] = DateTime.Now.ToString();
aCookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(aCookie);
//清除Cookie的正确代码(假设Cookie名称为UserInfo):
if (Request.Cookies["UserInfo"] != null)
{
Response.Cookies["UserInfo"].Expires = DateTime.Now.AddDays(-1);
}
//如果需要清除所有Cookie,则遍历:
for (int i = 0; i < Response.Cookies.Count; i++)
{
Response.Cookies[i].Expires = DateTime.Now.AddDays(-1);
}