OOP & concepts

SQL injection: what it is and how to prevent it in ASP.NET and SQL Server

OOP & concepts · · Published 2026-10-30

SQL injection happens when text supplied by a user is pasted into an SQL statement and the database ends up executing part of that text as code. It is one of the oldest web vulnerabilities and still one of the most damaging, because a single injectable query can expose or alter an entire database. The fix is well known and cheap: keep data and code apart by using parameters.

A vulnerable query

Here is the kind of login check that still turns up in legacy Web Forms code:

// DO NOT USE: vulnerable to SQL injection
string sql = "SELECT COUNT(*) FROM Users WHERE UserName = '" + txtUser.Text +
             "' AND PasswordHash = '" + Hash(txtPassword.Text) + "'";

using (var con = new SqlConnection(connectionString))
using (var cmd = new SqlCommand(sql, con))
{
    con.Open();
    int matches = (int)cmd.ExecuteScalar();
    loggedIn = matches > 0;
}

If the user types alice, the statement is what the developer expected. If the user types this in the user name box:

' OR 1=1 --

the database receives:

SELECT COUNT(*) FROM Users WHERE UserName = '' OR 1=1 --' AND PasswordHash = '...'

The quote closes the string literal, OR 1=1 makes the condition true for every row, and -- turns the rest of the statement into a comment. The count is the number of users, so the login succeeds without a password.

Logging in is the mild case. Depending on the query and the account's permissions, injected text can read other tables with UNION SELECT, extract data one bit at a time through timing (WAITFOR DELAY) or error messages, modify or delete rows, and on a badly configured server reach the operating system.

Why escaping quotes is not the fix

A common first reaction is to replace ' with ''. That handles one case of one data type. Numeric values are concatenated without quotes ("... WHERE Id = " + id), so 1; DROP TABLE Orders needs no quote at all. Encoding tricks, second-order injection (a value stored safely, then concatenated into another query later) and identifiers such as column names are not covered either. Escaping tries to clean the code after mixing it with data; parameters avoid mixing them.

Defence 1: parameterised commands

With a parameter, the SQL text is fixed and the value travels separately to SQL Server, which treats it as data whatever it contains:

using System.Data;
using Microsoft.Data.SqlClient; // or System.Data.SqlClient on older projects

const string sql =
    "SELECT COUNT(*) FROM dbo.Users WHERE UserName = @user AND PasswordHash = @hash";

using (var con = new SqlConnection(connectionString))
using (var cmd = new SqlCommand(sql, con))
{
    cmd.Parameters.Add("@user", SqlDbType.NVarChar, 100).Value = txtUser.Text;
    cmd.Parameters.Add("@hash", SqlDbType.VarBinary, 64).Value = Hash(txtPassword.Text);

    con.Open();
    loggedIn = (int)cmd.ExecuteScalar() > 0;
}

Now ' OR 1=1 -- is simply a user name that does not exist. The same applies to every statement type: INSERT, UPDATE, DELETE and LIKE searches.

// LIKE: put the wildcards in the value, not in the SQL text
cmd.CommandText = "SELECT Name FROM dbo.Products WHERE Name LIKE @term";
cmd.Parameters.Add("@term", SqlDbType.NVarChar, 102).Value = "%" + search + "%";

If the search text may itself contain %, _ or [, escape those characters for LIKE (for instance by wrapping them in brackets); that is about matching rules, not about injection.

Prefer Parameters.Add with an explicit SqlDbType and size over AddWithValue. Both are safe against injection, but AddWithValue infers the type from the .NET value: a C# string becomes nvarchar of the string's length, which can force implicit conversions against varchar columns and creates a different cached plan for every length.

Defence 2: stored procedures, called properly

A stored procedure called with CommandType.StoredProcedure and parameters is safe in the same way:

using (var cmd = new SqlCommand("dbo.GetOrdersByCustomer", con))
{
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add("@CustomerId", SqlDbType.Int).Value = customerId;
    // ...
}

Stored procedures are not automatically safe, though. A procedure that builds a string and runs it with EXEC reintroduces the problem inside the database:

-- Vulnerable: dynamic SQL built by concatenation
CREATE PROCEDURE dbo.SearchProducts @Name nvarchar(100)
AS
    EXEC('SELECT ProductId, Name FROM dbo.Products WHERE Name = ''' + @Name + '''');

When dynamic SQL is unavoidable, pass values with sp_executesql, which accepts parameters:

CREATE PROCEDURE dbo.SearchProducts @Name nvarchar(100)
AS
BEGIN
    DECLARE @sql nvarchar(max) =
        N'SELECT ProductId, Name FROM dbo.Products WHERE Name = @p';
    EXEC sys.sp_executesql @sql, N'@p nvarchar(100)', @p = @Name;
END

Defence 3: allow-lists for things that cannot be parameters

Parameters carry values, not identifiers. A sortable grid that puts a column name into ORDER BY cannot use @column. Map the user's choice to a fixed set of known names instead:

static readonly Dictionary<string, string> SortColumns =
    new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
    {
        ["name"] = "Name",
        ["price"] = "UnitPrice",
        ["date"] = "CreatedOn"
    };

string column = SortColumns.TryGetValue(Request.QueryString["sort"] ?? "", out var c) ? c : "Name";
string direction = Request.QueryString["dir"] == "desc" ? "DESC" : "ASC";
string sql = "SELECT ProductId, Name, UnitPrice FROM dbo.Products ORDER BY " + column + " " + direction;

Only strings written by the developer reach the SQL text. In T-SQL, QUOTENAME() serves the same purpose for object names inside dynamic SQL.

Defence 4: limit the damage

ORMs and query builders

Entity Framework, Dapper and similar libraries parameterise values for you when you use them as intended: LINQ queries, FromSqlInterpolated in EF Core or Dapper's anonymous-object parameters. They do not protect raw SQL you assemble yourself, such as FromSqlRaw with string concatenation, which has exactly the same flaw as the first example in this article.

Finding injectable code

Summary

ApproachProtects against injection?
String concatenation, with or without quote doublingNo
Parameterised SqlCommandYes
Stored procedure called with parameters, no dynamic SQL insideYes
Stored procedure using EXEC on a concatenated stringNo
Dynamic SQL through sp_executesql with parametersYes, for values
Identifiers chosen from an allow-list or wrapped in QUOTENAMEYes

The difference between the ADO.NET execution methods used above is explained in ExecuteReader vs ExecuteNonQuery vs ExecuteScalar, and passing a whole table of values as one parameter in Passing a DataTable as a table-valued parameter.

Official documentation and references