【问题标题】:Postgres FromSqlRaw Doesn't take params correctlyPostgres FromSqlRaw 没有正确使用参数
【发布时间】:2020-07-20 07:59:36
【问题描述】:

TL&DR:

  1. 当我在 FromSqlRaw 之外执行字符串插值时,SQL 命令起作用。
  2. 当我使用 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


【解决方案1】:

抱歉没有在电脑前测试,可能是这样的:

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();

【讨论】:

  • 端到端示例here.
【解决方案2】:

以上是所有情况的“正确”答案,使用 Postgres 时除外

  var searchParam = new NpgsqlParameter("searchParam", $"%{search_string}%");
  var results = await this._context.getDashboardSearchIpAddresses.FromSqlRaw("select id, split_part(text(ipaddress),'/',1) as ipaddress, country_code, country_name, count(*) OVER() as total_count from ipaddresses where ipaddress::text LIKE @searchParam limit 8;", searchParam).ToListAsync();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-21
    • 1970-01-01
    • 2016-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多