简体   繁体   中英

How to get data in ASP.net MVC

I'm trying to get the IsAdmin Value with SQL query(This query return 1 line or 0). but i get this error {"invalide reading Tentative there are no any data present."} This is my code

        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;

    }

You are open to horrible SQL injection . Your site will be pwned by hackers the very same second you put it online if you don't use parametrized queries.

Like this:

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"));
        }
    }
}

You need to call

re.Read();

to move the reader to the first record before attempting to access the data. re.HasRows does not cause the reader to move to the first record.

Also, definitely use parameterized queries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM