实现会话持久化(Permanent Session)

80酷酷网    80kuku.com

  session|session  
//注意,需要引用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文件中。

分享到
  • 微信分享
  • 新浪微博
  • QQ好友
  • QQ空间
点击: