c# - 从用户输入中获取查询

标签 c# sql entity-framework security sql-injection

我需要实现一个休息端点,它应该接受查询作为输入。如下所示:

api.com/api/v1/users/(registrationDate eq '2018-07-01') AND ((height gt 160) OR (height lt 68))

此类查询不需要任何联接。并且实体的所有字段都可以包含在查询中。

我首先想到的是将此查询输入直接转换为 SQL 查询的 where 子句,

Dictionary<string, string> Operators = new Dictionary<string, string>
{
    { " eq ", " = " },
    { " ne ", " != " },
    { " gt ", " > " },
    { " gte ", " >= " },
    { " lt ", " < " },
    { " lte ", " <= " }
};

public string SQLify<T>(string query)
{
    if (query == null)
    {
        return $"SELECT * FROM [{typeof(T).Name}]";
    }

    foreach (var op in Operators)
    {
        query = query.Replace(op.Key, op.Value);
    }

    return $"SELECT * FROM [{typeof(T).Name}] WHERE ({query})";
}

并像这样使用它:

query = queryService.SQLify<User>(query);
var users = DbContext.Users.SqlQuery(query);

但正如您可能猜到的那样,我非常担心这可能带来的安全影响。我实际上尝试编写一些验证方法,检查括号的嵌套,并检查提到的字段实际上是类 T 的成员,但我确信它们提供的安全性是不够的。 p>

在这种情况下最好的方法是什么?

最佳答案

也许带有 OData 端点的 WebAPI 应该可以解决问题。

关于c# - 从用户输入中获取查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51226637/

相关文章:

c# - SQL检查表是否存在于C#中,如果不存在则创建

c# - Linq如何写一个JOIN

c# - 在一个 Controller 中使用 GUID 作为参数?

c# - MethodInvoker 与 Control.Invoke

c# - MonoDevelop - csproj 文件中的通配符

c# - Entity Framework 如何使用导航属性

c# - 无法加载文件或程序集工具\EntityFramework .PowerShell.Utility.dll'

c# - 如何获取文本文件的内容并将其复制到剪贴板?

sql - 扁平化 SQL 中的日期间隔

mysql - SQL 与 If 不同