自訂類實現ASP.NET的統一身分識別驗證

來源:互聯網
上載者:User

    在ASP.NET開發過程中,經常會進行身分識別驗證。比較麻煩的做法是,對每個頁面添加驗證代碼。我們知道,ASP.NET的頁面都繼承自System.Web.UI.Page類,我們可以自訂一個類,讓它繼承自Page類,並在該類中添加驗證操作。然後讓需要驗證的頁面類,繼承自我們定義的這個類,就可以實現統一驗證功能。

1、建立用於驗證頁面的基類BasePage,該類繼承自Page類

using System;using System.Data;using System.Linq;using System.Collections.Generic;using System.Web;using System.Web.UI;using System.Web.Security;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;/// <summary>/// 所有需要驗證的頁面基類/// </summary>public class BasePage : System.Web.UI.Page{    /// <summary>    /// 建構函式    /// </summary> public BasePage()    {        //添加Load事件的處理方法 this.Load += new EventHandler(BasePage_Load);    }    //頁面載入時執行驗證 void BasePage_Load(object sender, EventArgs e)    {        //擷取Session if (object.Equals(Session["UserID"], null))        {            //跳轉到登陸介面 this.Response.Redirect("~/Login.aspx");        }    }}

 

2、所有需要驗證的介面,繼承自BasePage類

    建立一個頁面demo.aspx,該頁面需要有驗證操作,則將該頁面的基類由Page改為BasePage:

public partial class demo : System.Web.UI.Page

    更改為:

public partial class demo : BasePage

 

    更改以後,demo.aspx頁面載入時,將會檢測Session中的UserID,為空白的話,將跳轉到註冊登入介面。以後需要驗證的頁面,都繼承自Basepage類就OK了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.