(五)创建Logon.aspx页面
1.在已创建好的项目里创建一个新的Web 窗体,名为Logon.aspx。
2.在编辑器里打开Logon.aspx,切换到HTML视图。
3.复制下面代码,然后在编辑菜单里“选择粘贴为HTML”选项,插入到
 1
 2   Logon Page
 3
 4
 5   
 6      Email: 
 7      
 8      
10           ID="vUserName" />
11   
12   
13      Password: 
14      
15      
17          ID="vUserPass" />
18      
19   
20   
21      Persistent Cookie: 
22      
23      
24   
25
26
27
28这个页面用来显示一个登录表单以便用户可以提供他们的用户名和密码,并且记录到应用程序中。
4.切换到设计视图,保存这个页面。
(六)编写事件处理代码来验证用户身份
 下面这些代码是放在后置代码页里的(Logon.aspx.cs)
1.双击Logon页面打开Logon.aspx.cs文件。
2.在后置代码文件里导入必要的名空间:
  using System.Data.SqlClient;
  using System.Web.Security;
3.创建一个ValidateUser的函数,通过在数据库中查找用户来验证用户的身份。(请改变数据库连接字符串来指向你的数据库)
 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
(注:这段代码的意思是先判断输入的用户名和密码是否符合一定的条件,如上,如果符合则连接到数据库,并且根据用户名来取出密码并返回密码,最后再判断取出的密码是否为空,如果不为空则再判断取出的密码和输入的密码是否相同,最后的false参数为不区分大小写)
4.在cmdLogin_ServerLick事件里使用下面两种方法中的一种来产生表单验证的cookie并将页面转到指定的页面。
下面提供了两种方法的示例代码,根据你的需要来选择。
a)在cmdLogin_ServerClick事件里调用RedirectFromLoginPage方法来自动产生表单验证cookie且将页面定向到一个指定的页面。
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)产生加密验证票据,创建回应的cookie,并且重定向用户。这种方式给了更多的控制权去让你如何去创建cookie,你也可以连同FormsAuthenticationTicket一起包含一些自定义的数据。
 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",',','); //创建一个验证票据
 9   cookiestr=FormsAuthentication.Encrypt(tkt,',',');//并且加密票据
10   ck=new HttpCookie(FormsAuthentication.FormsCookieName,cookiestr,',',');// 创建cookie
11   if(chkpersistCookie.Checked) //如果用户选择了保存密码
12    ck.Expires=tkt.Expiratioin;//设置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.请确保在InititalizeComponent方法里有如下代码:
   this.cmdLogin.ServerClick += new System.EventHandler(this.cmdLogin_ServerClick,',',');
(七)创建一个Default.aspx页面
这一节创建一个测试页面用来作为当用户验证完之后重定向到的页面。如果用户第一次没有被记录下来就浏览到这个页,这时用户将被重定向到登录页面。
  1.把现有的WebForm1.aspx重命名为Default.aspx,然后在编辑器里打开。
2.切换到HTML视图,复制以下代码到
这篇文章适用于:
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)


 
                    