判断每个页面是否登以及捕捉页面异常录解决方案

通常我们需要在每个页面判断Session是否存在,据此来断定用户是否登录,如果没有登录,就跳转到Login页面。

如果每个页面都去写  

       if (Session["user"]==null)
        {
            Response.Redirect("login.aspx");
        }

下面介绍一种更简单的解决方案

asp.net页面.cs文件都是继承System.Web.UI.Page,鼠标指向page然后转到定义,我们就会看到page里面所有的数据,.cs 类文件是只读的,我们无法修改,就只能新建一个类去继承page ,然后重写里面的一些方法,然后再让所有的页面继承这个类。

先引用 Using System.Web.UI.Page;
public class Class1:Page
{

      //重写OnInit
    override protected void OnInit(EventArgs e)
    {   
     
  if (System.Web.HttpContext.Current != null)
            {
                
              base.OnInit(e);
             this.Error += new System.EventHandler(this.Page_Error);
             }

 

         //如果Session 不存在
        if (Session["user"]==null)
        {
            Response.Redirect("Login.aspx");
        }
    }

         /// <summary>
        /// 错误处理方法
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Error(object sender, System.EventArgs e)
        {
            try
            {
                Exception currentError = Server.GetLastError();
                string msg = "出错页面:" + Request.Url.ToString() + "               出错方法:" + currentError.TargetSite.ToString() + "                 错误信息:" + currentError.Message+"   日期"+DateTime.Now.ToString();
                Common.TextOperations.WriteException(msg);
                Server.ClearError();
            }
            catch
            {
      System.Web.HttpContext.Current.Response.Redirect("/Error.html");
            }
        }
}

}

 

之前页面是这样写的public partial class WebForm1 : Page

现在每个页面,继承class1 就行了。

public partial class WebForm1 : Class1

posted @ 2012-01-05 12:10  放哨De老鼠  阅读(834)  评论(10编辑  收藏  举报