gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:01:07 25 4
gpt4 key购买 nike

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

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 类的成员,但我确信它们提供的安全性是不够的。

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

最佳答案

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com