Session Session在ASP.NET中,表示客戶端(Goggle,Firefox,IE等)與伺服器端的會話,用來存儲特定會話信息,準確來說,是用來存儲特定用戶信息。當客戶端向伺服器發送一個請求時,如登陸用戶ID,伺服器接收到該請求,伺服器端Session產生一個與該登陸用戶相關的Sessi ...
Session
Session在ASP.NET中,表示客戶端(Goggle,Firefox,IE等)與伺服器端的會話,用來存儲特定會話信息,準確來說,是用來存儲特定用戶信息。當客戶端向伺服器發送一個請求時,如登陸用戶ID,伺服器接收到該請求,伺服器端Session產生一個與該登陸用戶相關的SessionID,並將SessioID返回給客戶端(Goggle,Firefox,IE等),在新會話開始時,伺服器將SessionID當做cookie存儲在用戶的瀏覽器中。
Session操作與Application類似,作用於用戶個人,所以,過量的存儲會導致伺服器記憶體資源的耗盡。
為什麼引入Session?大家知道,因為http是一種無狀態協議,因此,Session正彌補了這一缺陷。當然,Session作用遠遠不止於這些,這裡就不多論述。
優點:1.使用簡單,不僅能傳遞簡單數據類型,還能傳遞對象。
2.數據量大小是不限制的。
缺點:1.在Session變數存儲大量的數據會消耗較多的伺服器資源。
2.容易丟失。(重啟IIS伺服器時Session丟失)
ps:可以配置把Session數據存儲到SQL Server資料庫中,為了進行這樣的配置,程式員首先需要準備SQL Server數據伺服器,然後在運行.NET自帶安裝工具安裝狀態資料庫。 這種方式在伺服器掛掉重啟後都還在,因為他存儲在記憶體和磁碟中。
使用方法:1.在源頁面的代碼中創建你需要傳遞的名稱和值構造Session變數:Session["Name"]="Value(Or Object)";
2.在目的頁面的代碼使用Session變數取出傳遞的值。Result = Session["Nmae"]
註意:session不用時可以銷毀它,銷毀的方法是:清除一個:Session.Remove("session名"); 清除所有:Session.Clear();
(1)a.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="a.aspx.cs" Inherits="WebApplication.a" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="Label1" runat="server" Text="張君寶"></asp:Label> <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /> </div> </form> </body> </html>
(2)a.aspx.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication { public partial class a : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { Session["name"] = Label1.Text;//把label1的值放進Session Session.Timeout = 1;//設置Session的作用時間是一分鐘,一分鐘後Session失效 Response.Redirect("b.aspx"); } } }
(3)b.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="b.aspx.cs" Inherits="WebApplication.b" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> </div> </form> </body> </html>
(4)b.aspx.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WebApplication { public partial class b : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Label1.Text = Session["name"].ToString(); } } }
(5)運行a頁面,點擊Button後進入b頁面,一分鐘之後刷新頁面會報錯“未將對象實例化”,正常,那是因為Session已經失效!
ps:此文章是本人參考網上內容加上自己的理解整合而成,如無意中侵犯了您的權益,請與本人聯繫。