导航

关于Session过期的处理方法

Posted on 2014-02-14 13:34  杨彬Allen  阅读(1042)  评论(0)    收藏  举报

  之前做法一般是在母版页第一句就直接判断Session["User"]是否为null,为null就跳到登录页面。

  现在有新的方法也可以实现,且更好,实现思路如下:

  1、自定义一个空类SessionNullException,继承Exception。  

public class SessionNullException:Exception
{ }

  2、自顶一个BasePage类,继承Page,同时我们的User可以放在BasePage的CurrentUser中,CurrentUser中读写Session["User"],如果此时Session["User"]为null,就抛SessionNullException。就像这样:

        public static T_User CurrentUser
        {
            get
            {
                var httpContext = System.Web.HttpContext.Current;
                if (null != httpContext)
                {
                    if (httpContext.Session == null)
                    {
                        throw new ApplicationException("Session为null,读取当前用户失败");
                    }
                    T_User user = httpContext.Session[ConstKey.LOGIN_USER] as T_User;
                    if (null != user)
                    {
                        return user;
                    }
                    else
                    {
                        //return null;
                        throw new SessionNullException();
                        
                    }
                }
                throw new ApplicationException("System.Web.HttpContext.Current == null.");
            }
        }

  3、最后,在BasePage类中重写OnError事件:

        /// <summary>
        /// 出错处理
        /// </summary>
        /// <param name="e"></param>
        protected override void OnError(EventArgs e)
        {
            base.OnError(e);

            var error = Server.GetLastError();
            if (null != error)
            {
                if (error is System.Data.ConstraintException)
                {
                    var ce = new System.Data.ConstraintException(
                        string.Format("{0},{1}", error.Message,
                        "试图进行的操作与约束冲突!")
                        );
                    throw ce;
                }
                else
                {
                    if (error is SessionNullException)
                    {
                        this.Response.Redirect("~/Home/Login.aspx");
                    }
                    else
                    {
                        Session["Error"] = error;
                        this.Response.Redirect("~/Error.aspx");
                    }
                }
            }
        }