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 uname=@userName", 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 ) );
}
(注:这段代码的意思是先判断输入的用户名和密码是否符合一定的条件,如上,如果符合则连接到数据库,并且根据用户名来取出密码并返回密码,最后再判断取出的密码是否为空,如果不为空则再判断取出的密码和输入的密码是否相同,最后的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,并且重定向用户。这种方式给了更多的控制权去让你如何