我需要实现一个休息端点,它应该接受查询作为输入。如下所示:
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/