使用c#.net建立asp.net應用程式表單驗證

來源:互聯網
上載者:User

標籤:

開啟 Visual Studio .NET。
建立 ASP.NET Web 應用程式,並指定應用程式的名稱和位置。
在 Web.config 檔案中配置安全設定

本部分示範了如何添加和修改<身分識別驗證>和<授權>配置部分,以配置 ASP.NET 應用程式來使用表單型驗證。
在項目資源管理員中,開啟 Web.config 檔案。
將身分識別驗證模式更改為Forms(表單)。
3.插入 標記,並填入相應的屬性。(有關這些屬性的詳細資料,請參閱參考部分列出的 MSDN 文檔或 QuickStart 文檔。)複製以下代碼,然後單擊[編輯] 功能表上的“粘貼為 HTML”,以粘貼檔案 部分中的代碼:

protection=“All” path=“/” timeout=“30” />

在 部分中拒絕匿名使用者的訪問(如下所示):



建立一個樣本資料庫表格儲存體使用者詳細資料

本部示範了如何建立一個樣本資料庫表來儲存使用者的使用者名稱、密碼和角色。如果要將使用者角色儲存在資料庫中並實現角色型安全性,則需要角色列。
在“開始”菜單上,單擊“運行”,然後鍵入 notepad 以開啟記事本。
反白以下 SQL 指令碼代碼,按右鍵該代碼,然後單擊“複製”。在記事本中,單擊[編輯] 功能表上的“粘貼”以粘貼以下代碼:
if exists (select * from sysobjects where id =
object_id(N‘[dbo].[Users]‘) and OBJECTPROPERTY(id, N‘IsUserTable‘) = 1)
drop table [dbo].[Users]
GO
CREATE TABLE [dbo].[Users] (
[uname] varchar NOT NULL ,
[Pwd] varchar NOT NULL ,
[userRole] varchar NOT NULL ,
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Users] WITH NOCHECK ADD
CONSTRAINT [PK_Users] PRIMARY KEY NONCLUSTERED
(
[uname]
) ON [PRIMARY]
GO

INSERT INTO Users values(‘user1‘,‘user1‘,‘Manager‘)
INSERT INTO Users values(‘user2‘,‘user2‘,‘Admin‘)
INSERT INTO Users values(‘user3‘,‘user3‘,‘User‘)
GO

將該檔案另存新檔 Users.sql。
在 Microsoft SQL Server 電腦上,在查詢分析器中開啟 Users.sql。在資料庫列表中,單擊“pubs”,然後運行該指令碼。這將建立一個樣本使用者表,並使用此應用程式範例填充要使用的 Pubs 資料庫中的該表。
建立 Logon.aspx 頁

將一個新的 Web Form添加到名為 Logon.aspx 的項目中。
在編輯器中開啟 Logon.aspx 頁,並切換到 HTML 視圖。
複製以下代碼,然後使用[編輯] 功能表上的“粘貼為 HTML”選項將代碼插入到

標記之間:

Logon Page
Email:
Password:
Persistent Cookie:


此 Web Form用於向使用者提供登入表單,以便他們提供用於登入到應用程式的使用者名稱和密碼。
切換到“設計”視圖並儲存該頁。
對事件處理常式編碼,以便驗證使用者憑證

本部分介紹了位於程式碼後置頁面 (Logon.aspx.cs) 的代碼。
雙擊“Logon”開啟 Logon.aspx.cs 檔案。
匯入程式碼後置檔案中必需的命名空間:
using System.Data.SqlClient;
using System.Web.Security;

建立 ValidateUser 函數,以便通過尋找資料庫來驗證使用者憑證。(確保將連接字串更改為指向資料庫。)
private bool ValidateUser( string userName, string passWord )
{

SqlConnection conn;SqlCommand cmd;string lookupPassword = null;// Check for invalid userName.// userName must not be null and must be between 1 and 15 characters.if ( (  null == userName ) || ( 0 == userName.Length ) || ( userName.Length > 15 ) ){    System.Diagnostics.Trace.WriteLine( "[ValidateUser] Input validation of userName failed." );    return false;}// Check for invalid passWord.// passWord must not be null and must be between 1 and 25 characters.if ( (  null == passWord ) || ( 0 == passWord.Length ) || ( passWord.Length > 25 ) ){    System.Diagnostics.Trace.WriteLine( "[ValidateUser] Input validation of passWord failed." );    return false;}try{    // Consult with your SQL Server administrator for an appropriate connection    // string to use to connect to your local SQL Server.    conn = new SqlConnection( "server=localhost;Integrated Security=SSPI;database=pubs" );    conn.Open();    // Create SqlCommand to select pwd field from users table given supplied userName.    cmd = new SqlCommand( "Select pwd from users where [email protected]", conn );    cmd.Parameters.Add( "@userName", SqlDbType.VarChar, 25 );    cmd.Parameters["@userName"].Value = userName;    // Execute command and fetch pwd field into lookupPassword string.    lookupPassword = (string) cmd.ExecuteScalar();    // Cleanup command and connection objects.    cmd.Dispose();    conn.Dispose();}catch ( Exception ex ){    // Add error handling here for debugging.    // This error message should not be sent back to the caller.    System.Diagnostics.Trace.WriteLine( "[ValidateUser] Exception " + ex.Message );}// If no password found, return false.if ( null == lookupPassword ) {    // You could write failed login attempts here to event log for additional security.    return false;}// Compare lookupPassword and input passWord, using a case-sensitive comparison.return ( 0 == string.Compare( lookupPassword, passWord, false ) );

}

可使用兩種方法之一產生表單身分識別驗證 Cookie,並將使用者重新導向到 cmdLogin_ServerClick 事件中的相應頁。為兩種情形都提供了範例程式碼。可根據需要使用其中的一個。
調用 RedirectFromLoginPage 方法,以便自動產生表單身分識別驗證 Cookie,並將使用者重新導向到 cmdLogin_ServerClick 事件中的相應頁:
private void cmdLogin_ServerClick(object sender, System.EventArgs e)
{
if (ValidateUser(txtUserName.Value,txtUserPass.Value) )

FormsAuthentication.RedirectFromLoginPage(txtUserName.Value,    chkPersistCookie.Checked);else    Response.Redirect("logon.aspx", true);

}

產生身分識別驗證票證,對其進行加密,建立 Cookie,將其添加到響應中並重新導向使用者。這樣,您就可以更好地控制 Cookie 的建立方式了。在本例中還可包括自訂資料和 FormsAuthenticationTicket。
private void cmdLogin_ServerClick(object sender, System.EventArgs e)
{
if (ValidateUser(txtUserName.Value,txtUserPass.Value) )
{
FormsAuthenticationTicket tkt;
string cookiestr;
HttpCookie ck;
tkt = new FormsAuthenticationTicket(1, txtUserName.Value, DateTime.Now,
DateTime.Now.AddMinutes(30), chkPersistCookie.Checked, “your custom data”);
cookiestr = FormsAuthentication.Encrypt(tkt);
ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr);
if (chkPersistCookie.Checked)
ck.Expires=tkt.Expiration;

        ck.Path = FormsAuthentication.FormsCookiePath; 

Response.Cookies.Add(ck);

string strRedirect;
strRedirect = Request[“ReturnUrl”];
if (strRedirect==null)
strRedirect = “default.aspx”;
Response.Redirect(strRedirect, true);
}
else
Response.Redirect(“logon.aspx”, true);
}

確保將以下代碼添加到由 Web Form設計器產生的程式碼的 InitializeComponent 方法中。
this.cmdLogin.ServerClick += new System.EventHandler(this.cmdLogin_ServerClick);

建立一個 Default.aspx 頁面

本部分建立了一個使用者在進行身分識別驗證後被重新導向的測試頁面。如果使用者在沒有先登入到應用程式的情況下瀏覽此頁,則將他們重新導向到登入頁。
將現有 WebForm1.aspx 頁重新命名為 Default.aspx,並在編輯器中開啟它。
切換到 HTML 視圖,並將下面的代碼複製到 標記之間:

此按鈕用於登出表單身分識別驗證會話。
切換到“設計”視圖並儲存該頁。
匯入程式碼後置檔案中必需的命名空間:
using System.Web.Security;

雙擊 SignOut 開啟程式碼後置頁 (Default.aspx.cs),並在 cmdSignOut_ServerClick 事件處理常式中複製以下代碼:
private void cmdSignOut_ServerClick(object sender, System.EventArgs e)
{
FormsAuthentication.SignOut();
Response.Redirect(“logon.aspx”, true);
}

請確保以下代碼已添加到 Web Form設計器產生的程式碼的 InitializeComponent 方法中:
this.cmdSignOut.ServerClick += new System.EventHandler(this.cmdSignOut_ServerClick);

儲存並編譯項目。現在,您就可以執行該應用程式了。

使用c#.net建立asp.net應用程式表單驗證

相關文章

聯繫我們

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