Introduction
SQL Injection (SQLi) is one of the most dangerous and common vulnerabilities in web applications. It allows attackers to manipulate queries executed by your database, potentially leading to unauthorized data access, modification, or even complete database takeover.
As developers, it is our responsibility to ensure that applications are secure against such attacks. In this article, we will explore practical strategies and C# code examples to prevent SQL Injection in ASP.NET MVC , ASP.NET Core MVC , and Web API applications.
What Is SQL Injection?
SQL injection happens when user input is directly concatenated into SQL statements without proper sanitization or parameterization.
Vulnerable code:
string sql = "SELECT * FROM Users WHERE Username = '" + username + "'";If an attacker enters '; DROP TABLE Users; -- , the query becomes destructive and can delete your table.
Best Practices To Prevent SQL Injection
1. Always Use Parameterized Queries
The golden rule : never concatenate user input directly into SQL . Use parameters instead.
Secure Example (ADO.NET)
public User GetUserByName(string username)
{
const string sql = "SELECT Id, Username, Email FROM Users WHERE Username = @Username";
using (var conn = new SqlConnection(connectionString))
using (var cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add(new SqlParameter("@Username", SqlDbType.NVarChar, 256)
{
Value = username ?? (object)DBNull.Value
});
conn.Open();
using (var reader = cmd.ExecuteReader())
{
if (reader.Read())
{
return new User
{
Id = reader.GetInt32(0),
Username = reader.GetString(1),
Email = reader.GetString(2)
};
}
}
}
return null;
}2. Use ORM Safely (Entity Framework Core)
LINQ queries are safe by default:
var user = await _dbContext.Users
.Where(u => u.UserName == username)
.FirstOrDefaultAsync(); Unsafe (don’t do this):
var sql = $"SELECT * FROM Users WHERE UserName = '{username}'";
var users = _dbContext.Users.FromSqlRaw(sql).ToList();
Join the conversation! Your thoughts help the community grow.