首页 > 解决方案 > Postgres FromSqlRaw 没有正确使用参数

问题描述

TL&DR:

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

标签: c#postgresqlasp.net-core

解决方案


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

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

推荐阅读