實現會話持久化(Permanent Session) - 中國WEB開發者網絡 (http://www.webasp.net) -- 技術教程 (http://www.webasp.net/article/) --- 實現會話持久化(Permanent Session) (http://www.webasp.net/article/18/17915.htm) |
| -- 作者:未知 -- 發佈日期: 2005-04-25 |
|
//注意,需要引用System.Runtime.Serialization.Formatters.Soap.dll程序集 public const string SESSIONDATAPATH = "C:\SessionData\" ; private void Application_AcquireRequestState( object sender, EventArgs e) { System.IO.FileStream fs; System.Runtime.Serialization.Formatters.Soap.SoapFormatter sf = new System.Runtime.Serialization.Formatters.Soap.SoapFormatter(); try { //獲取特定的cookie,如果找不到,則退出. HttpCookie cookie = Request.Cookies["PermSessionID"]; if(cookie == null) { //如果找不到,則生成一個(使用偽隨機的SessionID) cookie = new HttpCookie("PermSessionID", Session.SessionID); //使該cookie在1星期之後到期 cookie.Expires = DateTime.Now.AddDays(7); //將其發往客戶端瀏覽器 Response.Cookies.Add(cookie); } //文件名等於該cookie的值 string permSessionId = cookie.Value; //生成數據文件的名稱 string filename = SESSIONDATAPATH + permSessionId.ToString() + ".xml"; //打開文件,如果出錯,則退出 fs = new System.IO.FileStream(filename, IO.FileMode.Open); //反序列化包含值的Hashtable Hashtable ht = (Hashtable)sf.Deserialize(fs); //將數據移到Session集合中 Session.Clear(); foreach( string key in ht.Keys ) { Session(key) = ht(key); } } Catch(Exception ex) {} Finally { if( fs != null ) fs.Close(); } } 以上代碼實現了會話持久話的過程,AquireRequestState事件處理程序中的代碼會試圖讀取一個名為PermSessionID的特殊的客戶端cookie。該cookie的值被視為一個XML(在服務器上)的名稱,該XML文件包含在前一個請求結束時保存下來的Session變量的值,因此代碼會在頁面看到新值之前填充Session集合。如果該cookie尚不存在,說明現在看到的是從客戶端發出的第一個請求。所以代碼會創建cookie,並在其內部存放獨一無二的字符串。同時也應該在ReleaseRequestState事件裡創建一個服務端的XML文件,將所有Session變量序列化到該XML文件中。 |
| webasp.net |