2013-03-07 24 views
1

如果用戶有效或無法傳遞標籤,我正在使用3層架構與應用程序設置.so你能指導我如何通過標籤無論用戶是否有效或不如何在三層架構中傳遞標籤

 public static int login(string UserName, string Password) 
      { 

       SqlConnection con = new SqlConnection(); 
       con.ConnectionString = GetConnectionString(); 
       con.Open(); 
       int userid = 0; 
       string selectstr = "select UserName,Password from Registration where UserName =' " + UserName + " ' And Password = ' " + Password + " ' "; 
       SqlCommand cmd = new SqlCommand(); 
       cmd.CommandText = selectstr; 
       cmd.CommandType = System.Data.CommandType.Text; 
       cmd.Connection = con; 
       userid = cmd.ExecuteNonQuery(); 
       cmd = null; 
       con.Close(); 

       return userid; 

      if(......... ?) 
{ 
labet.Text = " valid"; 
} else 
{ 
label.Text = " not valid"; 
+5

您正在使用'ADO.NET'架構,但你戰勝它的目的。請參數化查詢。 ':)' – 2013-03-07 09:53:00

+0

兄弟我想驗證用戶並顯示有效的消息或有效 – hitarth 2013-03-07 09:58:15

+0

**請不要連接這樣的SQL語句。最終有人會在用戶名字段中輸入「OR 1 = 1; - 」......注意SQL注入! – fguchelaar 2013-03-07 10:05:07

回答

1


userid = cmd.ExecuteNonQuery(); 

會給你一個對象。

您將不得不使用cmd.ExcuteReader()來代替。


或者您可以使用查詢

string selectstr = "select 
         count(UserName)        
        from 
         Registration 
         where 
         UserName ='" + UserName + "' 
         And Password = '" + Password + "'"; 

計數的用戶數量和看到的計數。

+0

您不希望這樣做,以避免SQL注入攻擊。 – 2013-03-07 10:15:38

+0

@Poldie謝謝你的關注。但是,如果您在將函數發送給函數之前使用'microsoft.security.application.encoder',它將不會受到影響。 – 2013-03-07 10:37:05

-1

您的代碼可以優化很多。首先我必須告訴你,你最好使用參數,try-catch和ExecuteScalar。 ExecuteScalar將返回一個單元整數。有了這個,你可以驗證用戶身份驗證。

編輯:

public static void login(string UserName, string password) 
    { 
     SqlConnection con = new SqlConnection(GetConnectionString()); 
     try 
     { 
      con.Open(); 

      string selectstr = "select count(id) from Registration where [email protected] And [email protected]"; 

      SqlCommand cmd = new SqlCommand(selectstr, con); 
      cmd.Parameters.AddWithValue("@username", username); 
      cmd.Parameters.AddWithValue("@password", password); 

      int result = cmd.ExecuteScalar(); 
      cmd.Dispose(); 
      con.Close(); 

      if (result == 1) 
      { 
       label.Text = "valid"; 
       //valid 
      } 
      else 
      { 
       //not 
      } 
     } 
     catch 
     { 
      throw; 
     } 
    } 
+0

你可以寫下代碼.... @ Doruk – hitarth 2013-03-07 10:03:30

+1

你想讓他爲你的網站挑選主機嗎? – 2013-03-07 10:13:37

+0

嘿我不能得到label.text它是無效的 – hitarth 2013-03-07 10:17:37