asp.net的身分識別驗證類型如下:
在我們實際的工作中,froms身分識別驗證用的還是比較多的,我們接下來詳細說一下:
做為web開發的程式員,我想登入表單是接觸的太多了。可是,我發現有的程式員在對身分識別驗證的時候是把驗證的使用者名稱儲存在一個session裡的,然後進入系統的每個頁面都去驗證session是否為空白,如果不為空白那麼就response.redirect("......aspx")。
我認為這種方法相對於asp.net提供的form身分識別驗證來說是不足的,首先,就是增加代碼量,因為我們在每個頁面都要驗證一下session是否存在;其次,session是儲存在伺服器記憶體中,我認為如果經常使用session勢必會拖慢伺服器的速度。而form身分識別驗證則不同,它是把資料儲存在cookie中的,所以,可以減輕伺服器的壓力。
舉例一:
在項目中添加兩個頁面:login.aspx(用來做登入頁面)和main.aspx(主介面)
如果我們添加了from身分識別驗證的話,那麼當然我們首先要先設定不允許匿名訪問網站,接著我們把通過身分識別驗證的使用者添加到cookie中,web設定檔如下:
<?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <compilation debug="true" targetFramework="4.0" /> <authentication mode="Forms"> <forms name="save" loginUrl="login.aspx" protection="All"> </forms> </authentication> <authorization> <deny users="?"/> </authorization> </system.web> </configuration>
說明:
進行設定後,如果我們直接存取main.aspx頁面,那麼會跳轉到login.aspx。
我們在登入按鈕下寫上如下代碼:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace LastTest { public partial class login : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { if (true) //可以通過查詢資料庫 驗證使用者是否合法 { //被注釋的這兩行語句相當於最下面的語句 就是儲存使用者後轉回到原來的頁面。 //System.Web.Security.FormsAuthentication.SetAuthCookie(TextBox1.Text, chkIsSavePwd.Checked); //Response.Redirect("main.aspx"); System.Web.Security.FormsAuthentication.RedirectFromLoginPage(TextBox1.Text, chkIsSavePwd.Checked); } else { } } } }
當然們也可以刪除身分識別驗證,退出登入,我們在主介面上加一個登出按鈕:
登出下的代碼:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace LastTest { public partial class main : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { //從瀏覽器刪除from驗證票證 System.Web.Security.FormsAuthentication.SignOut(); //重新回到登入頁面 Response.Redirect("login.aspx"); } } }
當然,如果一個系統就有幾個人用的話,那麼我們也可以添加固定使用者,然後對使用者的密碼可以進行加密:如果MD5加密或者SHA1,當然也可以使用clear(明文,不安全)。
以上就是關於ASP.NETt的表單身分識別驗證,希望對大家的學習有所協助。