【问题标题】:How do I Read OData URL parameter values in C# action?如何在 C# 操作中读取 OData URL 参数值?
【发布时间】:2019-06-28 23:38:58
【问题描述】:
我正在尝试读取 C# 中传递给 odata 请求的参数值
在下面的请求中,我传递了 $filter 并期望读取过滤器值
网址:http://localhost:57097/Lead?$filter=AssignedToID eq 21987 and IsDeleted eq false
我正在使用此代码读取参数值
HttpContext.Current.Request.QueryString.Get("$filter");
它返回 "AssignedToID eq 21987 and IsDeleted eq false"
但我希望读取 AssignedToID 即 21987 和 IsDeleted 即 false 的值
【问题讨论】:
标签:
c#
model-view-controller
parameters
odata
url-parameters
【解决方案1】:
第 1 步:从控制器操作中读取选项
public IQueryable<_MODELNAME_> Get(ODataQueryOptions<_MODELNAME_> Options)
{
......
}
第 2 步:从选项中读取 BinaryOperatorNode
var binaryOperator = Options.Filter.FilterClause.Expression as BinaryOperatorNode;
string filters = getWhereClause(binaryOperator);
第 3 步:创建以下递归函数以查找所有过滤器值
private static string getWhereClause(BinaryOperatorNode node)
{
var s = "";
if (node.Left is SingleValuePropertyAccessNode && node.Right is ConstantNode)
{
var property = node.Left as SingleValuePropertyAccessNode ?? node.Right as SingleValuePropertyAccessNode;
var constant = node.Left as ConstantNode ?? node.Right as ConstantNode;
if (property != null && property.Property != null && constant != null && constant.Value != null)
{
s += $" {property.Property.Name} {getStringValue(node.OperatorKind)} '{constant.Value}' ";
}
}
else
{
if (node.Left is BinaryOperatorNode)
s += getWhereClause(node.Left as BinaryOperatorNode);
if (node.Right is BinaryOperatorNode)
{
s += $" {getStringValue(node.OperatorKind)} ";
s += getWhereClause(node.Right as BinaryOperatorNode);
}
}
return s;
}