【问题标题】: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"

但我希望读取 AssignedToID21987IsDeletedfalse 的值

【问题讨论】:

  • 寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定问题或错误以及重现它所需的最短代码在问题本身(见minimal reproducible example)。没有明确问题陈述的问题对其他读者没有用,很可能不会得到回答。 有关更多帮助,请查看“How to ask

标签: 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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-13
    • 1970-01-01
    • 2019-10-28
    • 1970-01-01
    • 1970-01-01
    • 2015-03-18
    • 2016-05-22
    相关资源
    最近更新 更多