I am a new ASP.NET developer and I am developing a web-based application in which there is a menu bar that has many options. Some of these options will be displayed only to the Admin. There is a logic behind the system to check whether the user is an admin or not. If yes, the options will be displayed. I wrote the method but I have a sql injectiom and I want to remove it.
For your information, I have the following database design:
- Users table:
NetID, Name, Title - Admins table:
ID, NetID
Here’s the C# method:
private bool isAdmin(string username)
{
string connString = "Data Source=appSever\\sqlexpress;Initial Catalog=TestDB;Integrated Security=True";
string cmdText = "SELECT ID, NetID FROM dbo.Admins WHERE NetID = '" + NetID + "')";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
// Open DB connection.
using (SqlCommand cmd = new SqlCommand(cmdText, conn))
{
SqlDataReader reader = cmd.ExecuteReader();
if (reader != null)
if (reader.Read())
if (reader["ID"].Equals(1))
return true;
return false;
}
}
}
I tried to change it by doing the changing the third line to:
string cmdText = "SELECT ID, NetID FROM dbo.Admins WHERE NetID = @NetID)";
But I got the following error and I don’t know why:
Must declare the scalar variable “@NetID”.
Could you please help me in solving this?
**UPDATE:
After updating the code to the following:
private bool isAdmin(string username)
{
string NetID = username;
string connString = "Data Source=appServer\\sqlexpress;Initial Catalog=TestDB;Integrated Security=True";
string cmdText = "SELECT ID, NetID FROM dbo.Admins WHERE NetID = @NetID";
using (SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
// Open DB connection.
using (SqlCommand cmd = new SqlCommand(cmdText, conn))
{
cmd.Parameters.AddWithValue("@NetID", NetID);
SqlDataReader reader = cmd.ExecuteReader();
if (reader != null)
if (reader.Read())
if (reader["NetID"] == username)
return true;
return false;
}
}
}
I got the following error:
Incorrect syntax near ‘)’.
How to fix this problem?
Try this