大家好,我是ASP.net的新手,正尝试构建我认为简单的重定向页面。我已经有一个IIS基本身份验证设置,并且成功登录的用户访问下面的default.aspx页。我有一个数据库,在该数据库中创建了用户登录名的副本并为他们创建了group_id。我想做的是,登录成功后,用户将到达下面的默认页面,并检查该用户是否是group_ID 1001的一部分,答案是肯定的,以将其重定向到URL1,否则将其重定向到URL2。
我已经从该站点上的人员那里获得了很多帮助,并为我提供了有关不同编码语言的示例,认为我可以轻松地翻译它们,但会陷入不同的步骤。现在,我遇到了以下错误,并试图理解其逻辑。希望从那里获得VB Net专家的建议。非常感谢您的帮助,但是现在已经坚持了好几天。
更新的代码-3月1日
%@ Page Language="VB" debug="true" %>
<%@ Import Namespace = "System.Data" %>
<%@ Import Namespace = "MySql.Data.MySqlClient" %>
<script language="VB" runat="server">
Sub Page_Load(sender As Object, e As EventArgs)
Dim username As String = Convert.ToString(User.Identity.Name.Substring(User.Identity.Name.IndexOf("\") + 1))
Dim myConnection As MySqlConnection
Dim myDataAdapter As MySqlDataAdapter
Dim strSQL As String
Dim mySqlCommand As MySqlCommand
Dim counter As Integer
Dim isInGroup As Boolean
myConnection = New MySqlConnection("server=localhost; user id=Directory_Admin; password=IMCisgreat2014; database=imc_directory_tool; pooling=false;")
strSQL = "SELECT COUNT(*) FROM tbl_staff WHERE username = @username AND 'group_id' = '1001';"
myDataAdapter = New MySqlDataAdapter(strSQL, myConnection)
mySqlCommand = New MySqlCommand(strSQL)
mySqlCommand.Parameters.AddWithValue("@username", username)
counter = mySqlCommand.ExecuteScalar()
myConnection.Open()
If isInGroup = counter > 0 Then
Response.Redirect("http://www.w3schools.com")
Else
Response.Redirect("http://www.google.ca")
End If
myConnection.Close()
End Sub
</script>
<html>
<head>
<title>Simple MySQL Database Query</title>
</head>
<body>
Main page ...
</body>
</html>
我收到以下错误:
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: Connection must be valid and open.
Line 18: mySqlCommand = New MySqlCommand(strSQL)
Line 19: mySqlCommand.Parameters.AddWithValue("@username", username)
Line 20: counter = mySqlCommand.ExecuteScalar()
Line 21: If isInGroup = counter > 0 Then
Line 22: Response.Redirect("http://www.w3schools.com")
最佳答案
您创建了MySqlConnection,但从未将MySqlCommand连接到它。
mySqlCommand.Connection = mySqlConnection
mySqlCommand.Connection.Open()
另外,在您调用ExecuteScalar之后,请不要忘记使用以下命令关闭连接
mySqlCommand.Connection.Close()
否则,您的连接将保持打开状态并悬空。