2012-04-02 102 views
0

我想获取IsAdmin值与SQL查询(此查询返回1行或0)。但我得到这个错误{“invalide阅读暂定有没有存在的任何数据。”} 这是我的代码如何在ASP.net中获取数据MVC

 public static bool Login (string iduser, string password, bool IsAdmin) 
    { 
     bool auth = false; 
     string query = string.Format("Select IsAdmin from [user] where iduser = '{0}' AND mdp = '{1}' ;", iduser, password); 
     SqlCommand cmd = new SqlCommand(query, con); 
     con.Open(); 
     SqlDataReader re = cmd.ExecuteReader(); 
     auth = re.HasRows; 
     if (auth) { IsAdmin = re.GetBoolean(0); } // the error is on this line (this line will alow me to get IsAdmin Value If the user exist) 
     con.Close(); 
     return auth; 

    } 
+0

也许有人使用SQL Injection攻击了您的网站并删除了所有用户?另外,SqlDataReader是IDisposable。 – 2012-04-02 21:15:12

+0

这不是您的问题的答案,但是您的SQL查询方式很容易受到SQL注入攻击。您应该始终使用参数化查询。 – 2012-04-02 21:16:36

+0

哦,这让我渴望输入像''的密码; drop table [user]; - ' – 2012-04-03 10:44:27

回答

6

你是开放的可怕SQL injection。如果您不使用参数化查询,您的网站将被黑客运用,就像您在网上放置它一样。

像这样:

public static bool IsAdmin(string iduser, string password) 
{ 
    using (var conn = new SqlConnection(ConnectionString)) 
    using (var cmd = conn.CreateCommand()) 
    { 
     conn.Open(); 
     cmd.CommandText = @" 
      SELECT IsAdmin 
      FROM [user] 
      WHERE iduser = @iduser AND mdp = @mdp; 
     "; 
     cmd.Parameters.AddWithValue("@iduser", iduser); 
     cmd.Parameters.AddWithValue("@mdp", password); 
     using (var reader = cmd.ExecuteReader()) 
     { 
      return reader.Read() && reader.GetBoolean(reader.GetOrdinal("IsAdmin")); 
     } 
    } 
} 
+2

+1击败了我 – 2012-04-02 21:16:30

0

你需要调用

re.Read(); 

试图访问数据之前,读者移到第一条记录。 re.HasRows不会导致读者移到第一个记录。

另外,绝对使用参数化查询。

相关问题