抛弃asp.net的Session改用自己的Session..嘎嘎

来源:互联网 发布:异界修真淘宝店百度云 编辑:程序博客网 时间:2024/05/16 15:11


最近做.net项目,这个项目有点特殊,需要在每次http请求结束后,自动在文档的最后面加个字符串....

但是这个字符串需要用到Session....

 

结果我就在httpMoudle中加了一个过滤器.

 

当请求结束时把返回的数据 进行处理

 

用普通的过滤器不能满足要求..因为在contextApplication.EndRequest 事件触发的时候 Session已经销毁了..

所以不能访问Session...

 

思来想去,方法有两种..

第一种:新建一个集成自System.Web.UI.Page类的子类.然后所有的子页面都继承我写的这个类..这样Session也能用.也能达到效果...

缺点:.工作量太大..好多的页面要改呢.

 

第二种:自己创建Session,自己管理Session,完全抛弃 asp.net本身提供的Session...  

缺点,难度有点大...

优点: 以后可以自己随便使用Session ..不会出现Session相关的异常...

风险:可能自己想的不够周期,会出现一些漏洞..

 

不过俺是个喜欢挑战的人...喜欢自己控制事物.所以俺挑了第二种方案... 俺心里明白这么做是典型的程序员思维...但俺还是选择了第二种方案..

谁也说不准下次会不会用上这种方案..

不过我还是很认可我的方案的..

效率比微软的效率要高多了...

不信你试试看啊..

而且是开源的...下次出问题可以自己搞定...

越来越不喜欢微软的构架师..总以为我们程序员是白痴...人为的加好多限制..搞的我们因为一个异常搞好几天,还不给源代码. 文档又写那么一大堆.

越来越发现开源的好啊..

废话不多说贴代码..

MySessionContext.cs 文件

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Web;using System.Threading;namespace ZGL.Session{    public class MySessionContext     {        ///         /// 自动销毁过期Session的线程        ///         private static Thread _AutoDestroyTimeOutSessionThread;              ///         /// 销毁超时Session的方法        ///         private static void DestroyTimeOutSession()        {            //1.查找过时的Seesion            Dictionary SessionPools = MySessionContext.SessionPools;            while (true)            //无限循环            {                Thread.Sleep(60000);//挂起1分钟后再执行                 //1.查找过时的Seesion                 DateTime now = DateTime.Now;                //20分钟的过期时间                var oldSessions = SessionPools.Where(session => (now - session.Value.LastUpdateTime).Minutes > 20)                                              .Select(p=>p.Key).ToArray();                //2.销毁                foreach (var item in oldSessions)                {                    SessionPools.Remove(item);                }            }        }        ///         /// 保存在服务端的Session池,单例且唯一        ///         ///         /// Dictionary         ///         public static readonly Dictionary SessionPools = new Dictionary();                static object mLockSeed = new object();                 ///         /// 取得当前Http请求所对应的MySession,如果本来没有MySession则会自动创建一个MySession.        ///         public static MySession CurrentSession        {            get            {                HttpContext context = HttpContext.Current;                MySession mySession = null;                string SessionId = null;                //创建超时守护线程.                if (_AutoDestroyTimeOutSessionThread == null)                {                    _AutoDestroyTimeOutSessionThread = new Thread(DestroyTimeOutSession);                    _AutoDestroyTimeOutSessionThread.Start();                }                //1.处理SessionID                if (  context.Request.Cookies.Count > 0     &&     context.Request.Cookies.Get("MySessionIdentification") != null   )                {                    SessionId = context.Request.Cookies.Get("MySessionIdentification").Value;                }                                 if (string.IsNullOrEmpty(SessionId))                {                    SessionId = Guid.NewGuid().ToString();                    //创建一个MySession                    HttpCookie mySessionCookie = new HttpCookie("MySessionIdentification", SessionId);                    mySessionCookie.HttpOnly = true;                    context.Response.AppendCookie(mySessionCookie);                                        //保证在当前的请求中不会重复创建新的MySession                     context.Request.Cookies.Add(mySessionCookie);                 }                //2.获取SessionID对应Session                SessionPools.TryGetValue(SessionId, out mySession);                //3.如果还是没有Session 就新建一个放到Session集合中                if (mySession == null)                {                    lock (SessionPools)                    {                        mySession = new MySession();                        mySession.SessionID = SessionId;                                            SessionPools.Add(SessionId, mySession);                    }                                    }                 return mySession;             }        }        }}


MySeesionHelper.cs文件

 

using System;using ZGL.Session;namespace ZGL.Common{    /**     * 本想把 MySessionContext.CurrentSession做成静态的变量好提高程序速度.但是后来一想不行..     * 静态的对象任何一个人访问的都是同一个对象...这样到时候Session就乱了..     * 想来想去没有更好的提高效率的方法.只能暂时先这么用着..效率估计也不低..     */    /// <summary>    /// Session助手类.    /// </summary>    public static class SessionHelper    {           /// <summary>        /// 移除seesion中指定的值        /// </summary>        /// <param name="name"></param>        /// <returns></returns>        public static void RemveSession(string name)        {            if (IsNull(name))            {                return ;            }            MySessionContext.CurrentSession.Remove(name);        }        /// <summary>        /// 获取seesion中指定的值        /// </summary>        /// <param name="name"></param>        /// <returns></returns>        public static string GetSession(string name)        {            if (IsNull(name))            {                return "";            }            return MySessionContext.CurrentSession.GetSession(name).ToString();        }        /// <summary>        /// 获取seesion中指定的值        /// </summary>        /// <param name="name"></param>        /// <returns></returns>        public static object GetObjectSession(string name)        {            if (IsNull(name))            {                return null;            }            return MySessionContext.CurrentSession.GetSession(name);        }        /// <summary>        /// 获取seesion中指定的int值        /// </summary>        /// <param name="name"></param>        /// <returns>如果没有值返回-1.</returns>        public static int GetIntSession(string name)        {            if (IsNull(name))            {                return -1;            }            return Convert.ToInt32(MySessionContext.CurrentSession.GetSession(name));        }        /// <summary>        /// 设置seesion中指定的值        /// </summary>        /// <param name="name"></param>        /// <returns></returns>        public static bool SetSession(string name, object value)        {            if (MySessionContext.CurrentSession == null )            {                return false;            }            MySessionContext.CurrentSession.SetSession(name, value);            return true;        }        /// <summary>        /// 判断Session中某个变量是否为null或""        /// </summary>        /// <param name="name">session中的变量名</param>        /// <returns></returns>        public static bool SessionIsNullOrEmpty(string name)        {            if (IsNull(name))            {                return true;            }            if (MySessionContext.CurrentSession.GetSession(name) == "")            {                return true;            }            return false;        }        /// <summary>        /// 检测是不是为空.        /// </summary>        /// <param name="name"></param>        /// <returns></returns>        private static bool IsNull(string name)        {             if (  MySessionContext.CurrentSession.GetSession(name) == null)            {                return true;            }            return false;        }        /// <summary>        /// 判断Session中某个变量是否有值         /// </summary>        /// <param name="name">session中的变量名</param>        /// <returns></returns>        public static bool SessionHasValue(string name)        {            return !SessionIsNullOrEmpty(name);        }    }}


 

MySession.cs文件

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Web;using System.Threading;public class MySession : Dictionary<string, Object>    {        /// <summary>        /// 会话ID        /// </summary>        public string SessionID { get; set; }        public void SetSession(string SessionName, object value)        {             LastUpdateTime = DateTime.Now;             this[SessionName] = value;        }        public Object GetSession(string SessionName)        {            LastUpdateTime = DateTime.Now;            Object v = null;            this.TryGetValue(SessionName, out v);            return v;        }        /// <summary>        /// 最好一次访问Session的时间        /// </summary>        public DateTime LastUpdateTime = DateTime.Now;    }


 

使用方法

if (SessionHelper.SessionHasValue("MemberName"))                        {                             reStr = "您好,<span style='color:red'>" + SessionHelper.GetSession("MemberName") + "</span>欢迎您回来!  【<a href='" + ExitURL + "'>退出管理</a>】";                        }