關於ASP.NET頁面類繼承的問題

來源:互聯網
上載者:User
代碼

//關於ASP.NET頁面類繼承的問題
//ASP.NET的後台代碼CS是一個繼承於System.Web.UI.Page的類
//如果想寫一公用的方法,如用Cookie或者Session判斷使用者是否登入系統.
//可自訂一個繼承於System.Web.UI.Page的類
//例如:
namespace HttpContextProj
{
    public class MyPage:System.Web.UI.Page
    {
        public MyPage()
        {
            //??
        } 
    }        
}
//在建立的頁面的後台代碼繼承這個類;例如:
public partial class _Default :MyPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //
            // HttpContext.Current.Session["name"] = "123";
        }
    }
//在Page_Load方法執行以前很多的Page對象是不能用的,例如Cookie,Application,Session
//要解決這個問題要在自訂的類中重寫Page_Load方法,OnInit()和InitializeComponent方法.
//完整的自訂類
public class MyPage:System.Web.UI.Page
    {
        public MyPage()
        {
            //??
        }
        #region 頁面載入
        private void Page_Loadx(object sender, System.EventArgs e)
        {
            if (HttpContext.Current.Session["name"] == null)
            {
                HttpContext.Current.Response.Redirect("http://www.google.cn/", true);
            }
        }
        #endregion
        #region 初始化
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            InitializeComponent();//??
        }
        #endregion
        #region 載入組件
        private void InitializeComponent()
        {
            this.Load += new EventHandler(Page_Loadx);
        }
        #endregion
    }
    //在執行個體化_Default類的時候首先執行的是OnInit方法。它重寫了System.Web.UI.Page.OnInit。
    //然後調用InitializeComponent方法,而InitializeComponent方法又調用了Load事件,執行了Page_Load方法。
    //

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.