Application:
WebForm1.aspx: protected void Button1_Click(object sender, EventArgs e) { this.Application["t"] = 123; Response.Redirect("WebForm2.aspx"); // 页面跳转。等价于 HttpContext.Current.Response.Redirect("WebForm2.aspx"); } /////////////////////////////////////////// WebForm2.aspx: protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { if (Application["t"] != null) { this.Literal1.Text = this.Application["t"].ToString(); int count = (int)this.Application["t"]; count++; // 加解锁:作用防止大量用户同时访问造成的数据不准确。 this.Application.Lock(); // application加锁 this.Application["t"] = count; this.Application.UnLock(); // 释放锁 } } }
1.容易丢失。例如:代码做了修改重新编译启动。
2.可以多用户同时使用该数据。
Session:
WebForm1.aspx: protected void Button1_Click(object sender, EventArgs e) { // 设置session this.Session["user"] = "namejr"; Response.Redirect("WebForm2.aspx"); } protected void Button2_Click(object sender, EventArgs e) { Response.Redirect("WebForm2.aspx"); } /////////////////////////////////////////// WebForm2.aspx: protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { if (this.Session["user"] != null) { this.Literal1.Text = this.Session["user"].ToString(); } else { this.Literal1.Text = "未登录"; } } }
session的信息是存储在服务器的,但是为了服务器区别出是哪一个用户,会在用户本地产生一个cookie,为了防止用户禁用cookie,可以再web.config做如下设置:
<system.web> <!-- 开启debug --> <compilation debug="true" targetFramework="4.5" /> <httpRuntime targetFramework="4.5" /> <!-- 防止用户禁用本地cookie --> <sessionState cookieless="UseUri"></sessionState> </system.web>
Cookie:
string a = this.Request.Cookies["a"].Value; // 获取cookie的值 this.Response.Cookies.Add(new HttpCookie() { Name = "b", Value = "B", Expires = DateTime.Now.AddDays(1) }); // 添加cookie。等同于HttpContext.Current.Response.AppendCookie(new HttpCookie() { Name = "c", Value = "C", Expires = DateTime.Now.AddDays(1) });
ViewState:
使用ViewState的数据保留在每个单独的页面,不能够跨页面进行实现
this.ViewState["key"] = 123;
Server.Transfer 和 Response.Redirect:
// Response.Redirect protected void Button1_Click(object sender, EventArgs e) { // 使用Response.Redirect相当于在客户端进行页面的跳转,具体看导航栏便可知道 Response.Redirect("WebForm2.aspx"); } // Server.Transfer protected void Button2_Click(object sender, EventArgs e) { // Server.Transfer相当于在服务器完成页面的指向,导航栏现实的仍然是WebForm1.aspx Server.Transfer("WebForm2.aspx"); }