簡體   English   中英

從字符串“”到“布爾”類型的轉換無效

[英]Conversion from string “” to type 'Boolean' is not valid

我在ASP.NET的登錄表單上的標題中收到錯誤消息有沒有人知道我怎么能解決它? 非常感謝幫助

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
  Dim conn As New MySqlConnection

  conn.ConnectionString = ("server=localhost;port=3307;user=user;password=password;database=DB;")

  Try

    Dim SQL As String = "select * from users3 where uname = '" & txtUName.Text & "' AND password = '" & txtPwd.Text & "'"

    conn.Open()

    Dim cmd As New MySqlCommand(SQL, conn)
    Dim reader As MySqlDataReader = cmd.ExecuteReader

        reader.Read()
        Dim isValidLogin As Boolean
        Boolean.TryParse(reader.GetValue(1), isValidLogin)

        If isValidLogin Then
            Session("UserName") = txtUName.Text
      Response.Redirect("REGISTERPROP.aspx")
    Else
      Response.Write("Invalid Login")
    End If

  Catch ex As Exception
    Response.Write("An Error Occurred: " & ex.Message.ToString())
  End Try
End Sub

更改:

Dim isValidLogin = reader.GetValue(1)

至:

Dim isValidLogin As Boolean
Boolean.TryParse(reader.GetValue(1), isValidLogin)

好吧,這條消息幾乎是不言自明的。 您正在嘗試將空(零)字符串轉換為布爾值。 Boolean的唯一有效字符串值是(不區分大小寫) truefalse 你有其他問題。

  • 如果找不到用戶/密碼,您的查詢將返回0行(空集),如果找到用戶/密碼,則(大概)返回1行。 但是,您沒有檢查Read()方法的返回值:如果讀取了行,則返回truefalse otherwise返回false otherwise 您的查詢僅在成功匹配時返回一行:您應該在嘗試從中檢索數據之前檢查該行。

  • 此外,您的查詢具有SQL注入漏洞。 考慮使用參數化查詢或存儲過程。 如果有人在密碼字段中輸入(或簡單地發布)回到您的頁面,您認為可能會發生什么:

     ; drop table users3 ; 
  • 您似乎在數據庫中以明文形式存儲密碼。 與您的SQL注入漏洞一起使用,您可以讓您的系統和用戶受到威脅。 考慮使用SHA-256等安全散列算法對密碼進行salting並散列鹽漬密碼。

將您的查詢更改為

`select 'true' from user3 where ...`

並使用DbReader.ExecuteScalar()執行它,它返回結果集第一行的第一列,如果結果集為空,則返回null 然后你的邏輯就變得更簡單了

Dim isValidLogin = cmd.ExecuteScalar()
If isValidLogin IsNot Nothing And isValidLogin Then
  Session("UserName") = txtUName.Text
  Response.Redirect("REGISTERPROP.aspx")
Else
  Response.Write("Invalid Login")
End If

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM