2013-10-22 34 views
1

我創建了一個WCF的「登錄」Windows窗體應用程序, 如何發送輸入用戶名和密碼到WCF並檢查用戶名是否在SQL?c#WCF服務 - 如何獲得文本框輸入值

private void loginbt_Click(object sender, EventArgs e) 
{ 

    string username = textBox1.Text; 
    string password = textBox2.Text; 

    //check username and password are not empty 
    if (username.Trim().Length != 0 && password.Trim().Length != 0) 
    { 
     checkPassword.CustomerServiceClient service= new checkPassword.CustomerServiceClient(); 
     var enterPassword = service.checkPassword(username, password); 

     //check input value here with WCF? 

    } 
} 

我得到Index was outside the bounds of the array.例外,當我添加string getUsername = enterPassword[0].name;。它看起來像WCF沒有從文本框中獲得輸入值,換句話說checkPassword(null,null)。

public Customer[] checkPassword(string name, string password){ 
     List<Customer> customers = new List<Customer>(); 
     SqlConnection connection = new SqlConnection(
      "Data Source = 11111; Initial Catalog = 1111;" + 
     "User ID = 1111; Password = 11111"); 
     connection.Open(); 

     SqlCommand command = new SqlCommand("select customerId, customerName, address, password, phone from Customer where customerName='"+name+"'", connection); 
     SqlDataReader reader = command.ExecuteReader(); 
     if (reader.Read()){ 
      Customer newCustomer = new Customer(reader.GetString(1), reader.GetString(3)); 
      string correctPW = reader.GetString(3); 
      if (correctPW == password) 
      { 
       customers.Add(newCustomer); 
      } 
     } 
     reader.Close(); 
     connection.Close(); 
     return customers.ToArray(); 
} 

對不起,我真的很困惑這個問題,希望你能理解我的問題,謝謝你的幫助。

+0

我不太清楚你的問題是什麼。你到目前爲止取得了什麼成就,以及你錯過了什麼。它看起來像你的代碼已經做了你想要的:「service.checkPassword(username,password)」。 –

+0

我得到了「索引超出了數組的界限」。當我添加「string getUsername = enterPassword [0] .name;」時出現異常。它看起來像WCF沒有從文本框中獲得輸入值,換句話說checkPassword(null,null)。 – user2893761

+0

在service.checkPassword(用戶名,密碼)處設置一個斷點,然後找出這些值是否正確,如果它們是正確的,那麼它們應該傳遞給WCF服務,並且存在服務問題。現在您必須調試WCF客戶端和服務。 –

回答

0

由於您在執行順序中將usernamepassword進一步調用Trim,因此服務調用不可能被執行爲checkPassword(null, null)。如果兩個變量均爲空,您將在服務調用之前收到NullReferenceException

一個紅色標誌,我看到的是,你正在測試的username並決定讓服務呼叫時password修整(空白截斷)版本,但尚未你繼續前進,用純粹的形式將它們作爲參數時服務電話。難道說服務的行爲不像你認爲的那樣,因爲參數中有空白嗎?

您真正需要做的是在調用服務之前驗證usernamepassword的值。問自己,「我的服務是否使用指定的參數值正確響應?」問題可能與服務而不是調用者有關。你將不得不在這裏做一些老式的調試。這是我們不能爲你做的事情,所以脫掉襪子和鞋子,讓你的腳溼潤!

作爲一個附帶說明,看起來您是通過網絡以純文本傳遞密碼。中間人攔截這些信息並不困難(實際上可能很容易)。同樣的,我也可以看到你也開放SQL注入攻擊。知道你正在使用無參數內聯SQL,我可以告訴你我的用戶名是x' or 'a'='a,這將導致返回Customer表中的所有行。我不知道這是否會在您的案件中造成安全漏洞,但我希望您至少可以想象這可能會造成什麼樣的破壞。我只提到所有這些,因爲你的WCF似乎與安全有關。

0

解決了我的問題。

這是因爲我使用輸入的用戶名從sql中選擇數據,所以當我輸入一個不存在的用戶名時,它會給出錯誤。

謝謝大家。

+0

剛剛標記爲接受的答案並關閉帖子。然後它將幫助其他人。 –