【发布时间】:2020-07-20 07:59:36
【问题描述】:
TL&DR:
- 当我在 FromSqlRaw 之外执行字符串插值时,SQL 命令起作用。
- 当我使用 SQLRAW 并在函数内传递一个变量时。它不再有效,即使文档说它应该。
下面是一个工作执行字符串插值的不安全方法。
[HttpGet("/home/dashboard/search")]
public async Task<ActionResult> dashboard_search([FromQuery] string search_string)
{
var query_string = $"select id, country_code, country_name, count(*) OVER() as total_count from ipaddresses where ipaddress::text LIKE '%{search_string}%' limit 8;";
var results = await this._context.getDashboardSearchIpAddresses.FromSqlRaw(query_string).ToListAsync();
return Ok(results);
}
然而,这很容易受到 SQL 注入的攻击。
Microsoft 文档说明如下:
FromSqlInterpolated 类似于 FromSqlRaw 但允许您使用 字符串插值语法。就像 FromSqlRaw、FromSqlInterpolated 只能用于查询根。与前面的示例一样, value 被转换为 DbParameter 并且不易受 SQL 攻击 注射。
当我尝试使用 FromSqlRaw 时,我得到一个空结果集
[HttpGet("/home/dashboard/search")]
public async Task<ActionResult> dashboard_search([FromQuery] string search_string)
{
var results = await this._context.getDashboardSearchIpAddresses.FromSqlRaw("select id, country_code, country_name, count(*) OVER() as total_count from ipaddresses where ipaddress::text LIKE '%{0}%' limit 8;",search_string).ToListAsync();
return Ok(results); }
查看参考:https://docs.microsoft.com/en-us/ef/core/querying/raw-sql
【问题讨论】:
-
这是在 Postgres 中运行的;这是一个关键问题,因为以下内容不起作用
标签: c# postgresql asp.net-core