我正在尝试动态构造将具有X个条件的原始SQL查询。我正在使用此页面上的信息:https://docs.microsoft.com/en-us/ef/core/querying/raw-sql
目前我有类似的东西:
String rawQuery = "SELECT * FROM ItemsTable WHERE ";
foreach (f in FilterList) {
rawQuery = rawQuery + String.Format(f.condition, f.userInput);
// f.condition is something like "Name LIKE {0}"
}
var filteredItems = context.ItemsTable
.FromSql(rawQuery)
.ToList();
问题是,使用.FromSql()不能替换我的参数,因此我容易受到SQL注入攻击。
是否可以使用.FromSql()完成此任务?
或者,还有其他方法可以防止SQL注入吗?
答案 0 :(得分:1)
您可以将查询参数化,构建SqlParameters列表,然后将查询和参数传递到FromSql()
:
var rawQuery = new StringBuilder("SELECT * FROM ItemsTable WHERE ");
var sqlParameters = new List<SqlParameter>();
foreach (var f in FilterList) {
var parameterName = $"@p{FilterList.IndexOf(f)}";
var parameterizedCondition = string.Format(f.condition, parameterName);
// f.condition is something like "Name LIKE {0}"
rawQuery.Append(parameterizedCondition);
sqlParameters.Add(new SqlParameter(parameterName, f.userInput));
}
var filteredItems = context.ItemsTable
.FromSql(rawQuery.ToString(), sqlParameters)
.ToList();