ASP.NET Core Interview Question #146

What is SQL injection and how should it be prevented in ASP.NET Core applications?

Authentication, Authorization & Security Mid-Level Intermediate

Quick Interview Answer

SQL injection occurs when untrusted input is combined with SQL text in a way that changes the intended SQL command. The primary defense is parameterization.

Detailed Explanation

SQL injection occurs when untrusted input is combined with SQL text in a way that changes the intended SQL command. The primary defense is parameterization.

Entity Framework Core LINQ queries normally parameterize values. With raw SQL, ADO.NET, or Dapper, use parameter APIs rather than concatenating user input into command text. Input validation is useful for correctness but is not a substitute for parameterized SQL.

Code Example

// Parameterized EF Core query
var product = await db.Products
    .FirstOrDefaultAsync(p => p.Name == userInput);

// Avoid:
// $"SELECT * FROM Products WHERE Name = '{userInput}'";