我想使用允许我使用 Like 子句的 EF FromSqlInterpolated 或 FromSqlRaw 创建查询,但我不知道在不让应用程序受到 SqlInjection 攻击的情况下执行此操作的正确方法是什么。 第一种方法将我带到了以下代码
var results = _context.Categories.FromSqlInterpolated(
$"Select * from Category where name like {"%" + partialName + "%"}");
第一个测试工作正常,它在提供预期字符串时返回结果,而在我提供类似 ';select * from Category Where name='Notes'--%';
时什么也不返回
我仍然对 SqlInjection 了解不多,至少不足以让我对之前显示的查询感到安全。
有人知道查询是否安全,或者是否有正确的方法吗?
谢谢
最佳答案
The FromSqlInterpolated and ExecuteSqlInterpolated methods allow using string interpolation syntax in a way that protects against SQL injection attacks.
var results = _context.Categories.FromSqlInterpolated(
$"Select * from Category where name like {"%" + partialName + "%"}");
或者您也可以像这样将查询更改为 Linq-to-Entity
var results = _context.Categories.Where(p => p.name.Contains(partialName ));
关于entity-framework - 带有 Like 子句的 EF Core 原始查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60386183/