Overview
Injection flaws in ASP.NET Core enable attackers to alter application behavior by inserting or modifying data or commands. When untrusted input is concatenated into SQL, shell commands, or other interpretable contexts, attackers can bypass authentication, access or modify data, or execute arbitrary code on the host with the app's privileges.
In ASP.NET Core, these vulnerabilities often arise when developers build SQL queries with string concatenation or interpolation, or pass user input to raw ADO.NET commands or EF Core methods that are not parameterized. Even ORMs can be misused, for example by using FromSqlRaw with untrusted input or by composing dynamic SQL strings.
Mitigations include adopting parameterized queries, using EF Core or Dapper with parameters, validating and sanitizing inputs, and avoiding raw SQL unless necessary. Always prefer parameter binding, and enable least-privilege database accounts. Use code analysis to catch injection-prone patterns and consider automated tests and CI checks for inputs that would trigger injection.
No CVEs are provided in this guide; the goal is to establish safe coding practices to reduce the risk of injection across ASP.NET Core apps and to minimize blast radius if an injection vulnerability is found.
Code Fix Example
ASP.NET Core API Security Remediation
using System;\nusing System.Data.SqlClient;\n\nnamespace Demo\n{\n public class InjectionDemo\n {\n public void RunVulnerable(string username, string connectionString)\n {\n string unsafeQuery = \"SELECT * FROM Users WHERE Username = '\" + username + \"'\";\n using (var conn = new SqlConnection(connectionString))\n {\n var cmd = new SqlCommand(unsafeQuery, conn);\n conn.Open();\n var reader = cmd.ExecuteReader();\n // ...\n }\n }\n\n public void RunFixed(string username, string connectionString)\n {\n string safeQuery = \"SELECT * FROM Users WHERE Username = @username\";\n using (var conn = new SqlConnection(connectionString))\n {\n var cmd = new SqlCommand(safeQuery, conn);\n cmd.Parameters.AddWithValue(\"@username\", username);\n conn.Open();\n var reader = cmd.ExecuteReader();\n // ...\n }\n }\n }\n}\n