c# - Postgres FromSqlRaw 没有正确使用参数
问题描述
TL&DR:
- 当我在 FromSqlRaw 之外执行字符串插值时,SQL 命令起作用。
- 当我在函数中使用 SQLRAW 并传递一个变量时。它不再有效,即使文档说它应该。
下面是一种执行字符串插值的工作INSECURE 方法。
[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 只能用于查询根。与前面的示例一样,该值被转换为 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
解决方案
抱歉不在电脑前测试,可能是这样的:
var searchParam = new SqlParameter("searchParam", search_string);
var results = await this._context.getDashboardSearchIpAddresses.FromSqlInterpolated($"select id, country_code, country_name, count(*) OVER() as total_count from ipaddresses where ipaddress::text LIKE %{searchParam}% limit 8").ToListAsync();
或者使用 Raw:
var searchParam = new SqlParameter("searchParam", $"%{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 @searchParam limit 8;",searchParam).ToListAsync();
推荐阅读
- amazon-web-services - 如何将多部分表单数据保存到 AWS Lambda 中的文件
- python - 删除停用词 Python
- ansible - 将多个 ansible-vault 加密文件复制到远程服务器
- spring-batch - 处理后如何将文件移动到存档和错误文件夹
- intellij-idea - elm-package.json 无法加载
- javascript - 在 JavaScript AJAX 响应的下拉列表中获取重复值
- android - Android Pie 无法解析主机
- deep-learning - 使用 cntk 检查点进行预测
- angular - 在 Observable 数组中查找 Observable
- javascript - Mongo/Mongoose/Multer/FS 删除图像