c# - 如何避免在此 EF Core 查询中进行 SQL 注入(inject)?

标签 c# entity-framework-core

由于 EF Core 当前不在数据库中执行分组查询,我使用以下查询来完成工作(InvoiceQueryDbQuery 类型) :

long merchantId = 177;
var invTokens = new List<string> {"qasas", "efsac"};
string inClause = string.Join(",", invTokens);

string query = $@"SELECT i.Token, i.Balance, COALESCE(SUM(i.Amount), 0) AS ProcessingAmount
                  FROM inv.Invoices i
                  WHERE i.Token IN ({inClause})
                    AND i.MerchantId = {merchantId} 
                    AND i.Status = {(int)InvoiceStatus.Scheduled}
                  GROUP BY i.Token, i.Balance";

return await dbContext.InvoicesQuery.FromSql(query).ToListAsync();

上面的代码运行完美,但我不喜欢它,因为它给我一个“可能的 SQL 注入(inject)漏洞”的警告。我知道我可以使用 #pragma 来抑制这个警告(这就是我目前正在使用的)。

我已经尝试传递查询并将参数提供给 FromSql 方法,这很有效,但是进入 IN 子句的参数没有得到正确映射。 .

尝试使用 $"'{string.Join("', '", invTokens)}'" 但没有成功。

任何帮助将不胜感激

最佳答案

从 EF Core 2.0 开始,您可以使用 FormattableString,您可以在其中使用字符串插值进行查询。
String interpolation in FromSql and ExecuteSqlCommand
FormattableString Class

In EF Core 2.0 we added special support for interpolated strings to our two primary APIs that accept raw SQL strings: FromSql and ExecuteSqlCommand. This new support allows C# string interpolation to be used in a 'safe' manner.

文档中的示例:

var city = "London";
var contactTitle = "Sales Representative";

using (var context = CreateContext())
{
    context.Set<Customer>()
        .FromSql($@"
            SELECT *
            FROM ""Customers""
            WHERE ""City"" = {city} AND
                ""ContactTitle"" = {contactTitle}")
            .ToArray();
 }

这将产生:

@p0='London' (Size = 4000)
@p1='Sales Representative' (Size = 4000)

SELECT *
FROM ""Customers""
WHERE ""City"" = @p0
    AND ""ContactTitle"" = @p1

关于c# - 如何避免在此 EF Core 查询中进行 SQL 注入(inject)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55367514/

相关文章:

entity-framework-core - 核心 2 保持领域模型与数据库变化同步

c# - 找不到类型命名空间名称 IdentityUser

c# - IQueryable 迭代 : do I need ToListAsync()?

c# - 尝试确定进程 ID 时发生错误

c# - 如何在 C# MVC 中将用户存储在我的 SQLEXPRESS 数据库中?

c# - 类型上的 EF 核心实体

.net - 系统丢失方法异常 : Method not found: 'Void Microsoft.Extensions.Caching.Memory.MemoryCache..ctor'

c# - 使用 EF Core 加载未映射的属性

c# - 如何摆脱 Visual Studio 设计器抛出的 "Out of memory"异常?

c# - VSTO 中的加载项 - 如何使用带按钮的功能区从 Word 文档中获取文本