日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > C# >内容正文

C#

[转]在ASP.NET中如何用C#.NET实现基于表单的验证(二)

發(fā)布時(shí)間:2025/3/20 C# 18 豆豆
生活随笔 收集整理的這篇文章主要介紹了 [转]在ASP.NET中如何用C#.NET实现基于表单的验证(二) 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

(五)創(chuàng)建Logon.aspx頁(yè)面
1.在已創(chuàng)建好的項(xiàng)目里創(chuàng)建一個(gè)新的Web 窗體,名為L(zhǎng)ogon.aspx。
2.在編輯器里打開(kāi)Logon.aspx,切換到HTML視圖。
3.復(fù)制下面代碼,然后在編輯菜單里“選擇粘貼為HTML”選項(xiàng),插入到<form>標(biāo)簽之間。

?

?1<h3>
?2???<font?face="Verdana">Logon?Page</font>
?3</h3>
?4<table>
?5???<tr>
?6??????<td>Email:</td>
?7??????<td><input?id="txtUserName"?type="text"?runat="server"></td>
?8??????<td><ASP:RequiredFieldValidator?ControlToValidate="txtUserName"
?9???????????Display="Static"?ErrorMessage="*"?runat="server"?
10???????????ID="vUserName"?/></td>
11???</tr>
12???<tr>
13??????<td>Password:</td>
14??????<td><input?id="txtUserPass"?type="password"?runat="server"></td>
15??????<td><ASP:RequiredFieldValidator?ControlToValidate="txtUserPass"
16??????????Display="Static"?ErrorMessage="*"?runat="server"?
17??????????ID="vUserPass"?/>
18??????</td>
19???</tr>
20???<tr>
21??????<td>Persistent?Cookie:</td>
22??????<td><ASP:CheckBox?id="chkPersistCookie"?runat="server"?autopostback="false"?/></td>
23??????<td></td>
24???</tr>
25</table>
26<input?type="submit"?Value="Logon"?runat="server"?ID="cmdLogin"><p></p>
27<asp:Label?id="lblMsg"?ForeColor="red"?Font-Name="Verdana"?Font-Size="10"?runat="server"?/>
28這個(gè)頁(yè)面用來(lái)顯示一個(gè)登錄表單以便用戶可以提供他們的用戶名和密碼,并且記錄到應(yīng)用程序中。
4.切換到設(shè)計(jì)視圖,保存這個(gè)頁(yè)面。

(六)編寫事件處理代碼來(lái)驗(yàn)證用戶身份
 下面這些代碼是放在后置代碼頁(yè)里的(Logon.aspx.cs)
1.雙擊Logon頁(yè)面打開(kāi)Logon.aspx.cs文件。
2.在后置代碼文件里導(dǎo)入必要的名空間:
??using System.Data.SqlClient;
??using System.Web.Security;
3.創(chuàng)建一個(gè)ValidateUser的函數(shù),通過(guò)在數(shù)據(jù)庫(kù)中查找用戶來(lái)驗(yàn)證用戶的身份。(請(qǐng)改變數(shù)據(jù)庫(kù)連接字符串來(lái)指向你的數(shù)據(jù)庫(kù))
?1private?bool?ValidateUser(?string?userName,?string?passWord?)
?2{
?3SqlConnection?conn;
?4SqlCommand?cmd;
?5string?lookupPassword?=?null;
?6
?7//?Check?for?invalid?userName.
?8//?userName?must?not?be?null?and?must?be?between?1?and?15?characters.
?9if?(?(??null?==?userName?)?||?(?0?==?userName.Length?)?||?(?userName.Length?>?15?)?)
10{
11??System.Diagnostics.Trace.WriteLine(?"[ValidateUser]?Input?validation?of?userName?failed."?);
12??return?false;
13}

14
15//?Check?for?invalid?passWord.
16//?passWord?must?not?be?null?and?must?be?between?1?and?25?characters.
17if?(?(??null?==?passWord?)?||?(?0?==?passWord.Length?)?||?(?passWord.Length?>?25?)?)
18{
19??System.Diagnostics.Trace.WriteLine(?"[ValidateUser]?Input?validation?of?passWord?failed."?);
20??return?false;
21}

22
23try
24{
25??//?Consult?with?your?SQL?Server?administrator?for?an?appropriate?connection
26??//?string?to?use?to?connect?to?your?local?SQL?Server.
27??conn?=?new?SqlConnection(?"server=localhost;Integrated?Security=SSPI;database=pubs"?);
28??conn.Open();
29
30??//?Create?SqlCommand?to?select?pwd?field?from?users?table?given?supplied?userName.
31??cmd?=?new?SqlCommand(?"Select?pwd?from?users?where?uname=@userName",?conn?);
32??cmd.Parameters.Add(?"@userName",?SqlDbType.VarChar,?25?);
33??cmd.Parameters["@userName"].Value?=?userName;
34
35??//?Execute?command?and?fetch?pwd?field?into?lookupPassword?string.
36??lookupPassword?=?(string)?cmd.ExecuteScalar();
37
38??//?Cleanup?command?and?connection?objects.
39??cmd.Dispose();
40??conn.Dispose();
41}

42catch?(?Exception?ex?)
43{
44??//?Add?error?handling?here?for?debugging.
45??//?This?error?message?should?not?be?sent?back?to?the?caller.
46??System.Diagnostics.Trace.WriteLine(?"[ValidateUser]?Exception?"?+?ex.Message?);
47}

48
49//?If?no?password?found,?return?false.
50if?(?null?==?lookupPassword?)?
51{
52??//?You?could?write?failed?login?attempts?here?to?event?log?for?additional?security.
53??return?false;
54}

55
56//?Compare?lookupPassword?and?input?passWord,?using?a?case-sensitive?comparison.
57return?(?0?==?string.Compare(?lookupPassword,?passWord,?false?)?);
58
59}

60
(注:這段代碼的意思是先判斷輸入的用戶名和密碼是否符合一定的條件,如上,如果符合則連接到數(shù)據(jù)庫(kù),并且根據(jù)用戶名來(lái)取出密碼并返回密碼,最后再判斷取出的密碼是否為空,如果不為空則再判斷取出的密碼和輸入的密碼是否相同,最后的false參數(shù)為不區(qū)分大小寫)

4.在cmdLogin_ServerLick事件里使用下面兩種方法中的一種來(lái)產(chǎn)生表單驗(yàn)證的cookie并將頁(yè)面轉(zhuǎn)到指定的頁(yè)面。
下面提供了兩種方法的示例代碼,根據(jù)你的需要來(lái)選擇。
a)在cmdLogin_ServerClick事件里調(diào)用RedirectFromLoginPage方法來(lái)自動(dòng)產(chǎn)生表單驗(yàn)證cookie且將頁(yè)面定向到一個(gè)指定的頁(yè)面。
private?void?cmdLogin_ServerClick(object?sender,System.EventArgs?e)
{
??
if(ValidateUser(txtUserName.value,txtUserPass.Value))

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

}

b)產(chǎn)生加密驗(yàn)證票據(jù),創(chuàng)建回應(yīng)的cookie,并且重定向用戶。這種方式給了更多的控制權(quán)去讓你如何去創(chuàng)建cookie,你也可以連同F(xiàn)ormsAuthenticationTicket一起包含一些自定義的數(shù)據(jù)。
?1private?void?cmdLogin_ServerClick(object?sender,System.EventArgs?e)
?2{
?3??if(ValidateUser(txtUserName.value,txtUserPass.Value))?
?4??{
?5???FormsAuthenticationTicket?tkt;
?6???string?cookiestr;
?7???HttpCookie?ck;
?8???tkt=new?FormsAuthenticationTicket(1,txtUserName.value,DateTime.Now,DateTime.Now.AddMinutes(30),chkPersistCookie.Checked,"your?custom?data");?//創(chuàng)建一個(gè)驗(yàn)證票據(jù)
?9???cookiestr=FormsAuthentication.Encrypt(tkt);//并且加密票據(jù)
10???ck=new?HttpCookie(FormsAuthentication.FormsCookieName,cookiestr);//?創(chuàng)建cookie
11???if(chkpersistCookie.Checked)?//如果用戶選擇了保存密碼
12????ck.Expires=tkt.Expiratioin;//設(shè)置cookie有效期
13????ck.Path=FormsAuthentication.FormsCookiePath;//cookie存放路徑
14???Response.Cookies.Add(ck);
15???string?strRedirect;
16???strRedirect=Request["ReturnUrl"];
17???if(strRedirect==null)
18????strRedirect="default.aspx";
19???Response.Redirect(strRedirect,true);
20??}

21??else
22???Reponse.Redirect("logon.aspx",true);
23}

245.請(qǐng)確保在InititalizeComponent方法里有如下代碼:
???this.cmdLogin.ServerClick += new System.EventHandler(this.cmdLogin_ServerClick);
(七)創(chuàng)建一個(gè)Default.aspx頁(yè)面
這一節(jié)創(chuàng)建一個(gè)測(cè)試頁(yè)面用來(lái)作為當(dāng)用戶驗(yàn)證完之后重定向到的頁(yè)面。如果用戶第一次沒(méi)有被記錄下來(lái)就瀏覽到這個(gè)頁(yè),這時(shí)用戶將被重定向到登錄頁(yè)面。
??1.把現(xiàn)有的WebForm1.aspx重命名為Default.aspx,然后在編輯器里打開(kāi)。

??2.切換到HTML視圖,復(fù)制以下代碼到<form>標(biāo)簽之間:
<input type="submit" Value="SignOut" runat="server" id="cmdSignOut">
這個(gè)按鈕用來(lái)注銷表單驗(yàn)證會(huì)話。
??3.切換到設(shè)計(jì)視圖,保存頁(yè)面。
??4.在后置代碼里導(dǎo)入必要的名空間:
using System.Web.Security;
??5.雙擊SingOut按鈕打開(kāi)后置代碼(Default.aspx.cs),然后把下面代碼復(fù)制到cmdSingOut_ServerClick事件處理中:
??private void cmdSignOut_ServerClick(object sender,System.EventArgs e)
??{
???FormsAuthentication.SignOut();//注銷
???Response.Redirect("logon.aspx",true);
??}
??6.請(qǐng)確認(rèn)在InititalizeComponent方法中有以下代碼:
??this.cmdSignOut.ServerClick += new System.EventHandler(this.cmdSignOut_ServerClick);
??7.保存編譯項(xiàng)目,現(xiàn)在可以運(yùn)行這個(gè)應(yīng)用程序了。
(八)附加提示
??1.如果想要在數(shù)據(jù)庫(kù)里安全地存放密碼,可以在存放到數(shù)據(jù)到之前先用FormsAuthentication類里的HashPasswordForStoringInConfigFile函數(shù)來(lái)加密。(注:將會(huì)產(chǎn)生一個(gè)哈希密碼)
??2.可以在配置文件(Web.config)里存放SQL連接信息,以便當(dāng)需要時(shí)方便修改。
??3.可以增加一些代碼來(lái)防止黑客使用窮舉法來(lái)進(jìn)行登錄。例如,增加一些邏輯使用戶只能有兩三次的登錄機(jī)會(huì)。如果用戶在指定的登錄次數(shù)里無(wú)法登錄的話,可以在數(shù)據(jù)庫(kù)里設(shè)置一個(gè)標(biāo)志符來(lái)防止用戶登錄直到此用戶訪問(wèn)另一個(gè)頁(yè)面或者請(qǐng)示你的幫助。另外,也可以在需要時(shí)增加一些適當(dāng)?shù)腻e(cuò)誤處理。
??4.因?yàn)橛脩羰腔隍?yàn)證cookie來(lái)識(shí)別的,所以可以在應(yīng)用程序里使用安全套接層(SSL)來(lái)保護(hù)驗(yàn)證cookie和其它有用的信息。
??5.基于表單的驗(yàn)證方式要求客戶端的游覽器接受或者啟用cookies.
??6.在<authentication>配置節(jié)里的timeout參數(shù)用來(lái)控制驗(yàn)證cookies重新產(chǎn)生的間隔時(shí)間。可以給它賦一個(gè)適當(dāng)?shù)闹祦?lái)提供更好的性能和安全性。
??7.在Internet上的一些代理服務(wù)器或者緩沖可能會(huì)緩存一些將會(huì)重新返回給另外一個(gè)用戶的包含Set-Cookie頭的Web服務(wù)器響應(yīng)。因?yàn)榛诒韱蔚尿?yàn)證是使用cookie來(lái)驗(yàn)證用戶的,所以通過(guò)中間代理服務(wù)器或者緩沖的話可能會(huì)引起用戶會(huì)被意外地搞錯(cuò)為原本不是要發(fā)送給他的用戶。
???
???
參考文章:
??如果想要知道如何通過(guò)配置<credentials>節(jié)點(diǎn)存放用戶名和密碼來(lái)實(shí)現(xiàn)基于表單的驗(yàn)證的話,請(qǐng)參考以下GotDotNet ASP.NET QuickStart示例:
??基于表單的驗(yàn)證:http://www.gotdotnet.com/QuickStart/aspplus/default.aspx?url=/quickstart/aspplus/doc/formsauth.aspx
??如果想要知道如何使用XML文件來(lái)存放用戶名和密碼來(lái)實(shí)現(xiàn)基于表單的驗(yàn)證的話,請(qǐng)參考SDK文檔的以下示例:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconcookieauthenticationusinganxmlusersfile.asp
  如果想要知道更多的關(guān)于ASP.NET安全的話,請(qǐng)參考Microsoft .NET Framework Developer's Guide文檔:
ASP.NET 安全:  http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconaspnetwebapplicationsecurity.asp
 ??如果想知道更多關(guān)于System.Web.Security名空間的話,請(qǐng)參考:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemWebSecurity.asp
  如果想知道更多的關(guān)于ASP.NET配置的話,請(qǐng)參考Microsoft .NET Framework Developer's Guide文檔:
ASP.NET配置:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconaspnetconfiguration.asp
ASP.NET配置節(jié)點(diǎn):
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpgrfaspnetconfigurationsections.asp
??如果想知道更多關(guān)于ASP.NET安全指導(dǎo)的話,請(qǐng)參考MSDN:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/authaspdotnet.asp
??如果想知道更多關(guān)于ASP.NET的,請(qǐng)參考MSDN新聞組:
http://go.microsoft.com/fwlink/?linkid=5811&clcid=0x409

這篇文章適用于:
Microsoft ASP.NET (included with the .NET Framework 1.1)
Microsoft Visual C# .NET (2003)
Microsoft ASP.NET (included with the .NET Framework) 1.0
Microsoft Visual C# .NET (2002)
Microsoft SQL Server 2000 (all editions)
Microsoft SQL Server 7.0
Microsoft SQL Server 2000 64 bit (all editions)

總結(jié)

以上是生活随笔為你收集整理的[转]在ASP.NET中如何用C#.NET实现基于表单的验证(二)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。