2016-03-05 14 views
1

我正在創建一個登錄表單,它可以從創建的數據庫對用戶名和密碼進行身份驗證,代碼運行時沒有錯誤,但是在編寫任何用戶名或密碼時是不存在的,它記錄在數據庫中,我需要它給認證,使只有數據庫的用戶名登錄..爲什麼登錄控制C#爲任何用戶名和密碼提供身份驗證

using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Web; 
    using System.Web.UI; 
    using System.Web.UI.WebControls; 
    using System.Web.Configuration; 
    using System.Data; 
    using System.Data.SqlClient; 

    namespace WebApplication1 
    { 
     public partial class LoginTest : System.Web.UI.Page 
     { 
      private string strcon = WebConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString; 
      protected void Page_Load(object sender, EventArgs e) 
      { 
       this.UnobtrusiveValidationMode = System.Web.UI.UnobtrusiveValidationMode.None; 
      } 
      private bool UserLogin(string un, string pw) 
      { 
       SqlConnection conn = new SqlConnection(strcon); 
       SqlCommand cmd = new SqlCommand("Select id from student where [email protected] and [email protected]", conn); 
       cmd.Parameters.AddWithValue("@un", un); 
       cmd.Parameters.AddWithValue("@pw", pw); 
       conn.Open(); 
       string result = Convert.ToString(cmd.ExecuteScalarAsync()); 
       if (String.IsNullOrEmpty(result)) return false; return true; 

      } 
      protected void Login1_Authenticate(object sender, AuthenticateEventArgs e) 
      { 
       string un = Login1.UserName; 
       string pw = Login1.Password; 
       bool result = UserLogin(un, pw); 
       if (result) 
       { 
        e.Authenticated = true; 
        Session["username"] = un; 

       } 
       else e.Authenticated = false; 
      } 
     } 
    } 
+0

您是否驗證了您從「結果」中獲得的回覆?設置一個斷點並檢查「結果」的值是否爲無效的用戶名/密碼。 –

+2

另外應該說明:密碼​​永遠不會以純文本形式存儲在數據庫中。這樣做是非常不安全的,會讓你面對法律問題。將存儲在數據庫中的所有密碼進行哈希和散列 –

回答

2

cmd.ExecuteScalarAsync()返回Task對象。將其轉換爲字符串將始終成功;它會創建一個「System.Threading.Tasks.Task」字符串,它肯定不是空的,或者是null。

您需要await撥打電話ExecuteScalarAsync(),或者您需要撥打ExecuteScalarAsync().Result,這將阻止,直到查詢操作完成。

此外,請確保您正在製作的任何應用程序 - 即使您認爲它是玩具 - 正在使用適當的密碼單向散列。有大量的的建議在這裏Stackoverflow和其他地方如何安全地存儲密碼。

相關問題