繁体   English   中英

如何在 Azure API-manager 策略中创建和使用列表?

[英]How to create and use list in Azure API-manager policy?

背景:我在 Azure API 管理中定义了一个 API。 我已经定义了“所有操作”级别的策略。 这个政策做了几件事。 它所做的其中一件事是在上下文 object 中设置一个变量,因此我可以在 when 条件下重新使用该变量。

我需要帮助:

如何在 Azure API-M 策略中定义一个列表,我可以在什么条件下参考?

代码示例

所有运营政策:

<policies>
    <inbound>
        <base />
        <set-variable name="someList" value="[a,b,c,d]" />
        <when condition="@(context.Variables["someList"].Contains("a"))"
        </when>
        <otherwise>
        </otherwise>
    </inbound>
</policies>

看来我的问题是变量“someList”未被识别为数组,而是作为字符串 =“[a,b,c,d]”。 所以基本上,如果条件是 Contains("["),它将返回 true。

我也尝试将值存储为命名值,但命名值不能包含数组作为值。

我想要实现的是保留订阅列表,以便我可以将请求中的传入订阅密钥与预定义订阅密钥列表相匹配。

在使用.ContainsKey('key') 之前尝试将 context.Variables['somelist'] 解析为列表。 我从来不需要解析一个列表,所以你必须用谷歌搜索它是怎么做的,为此使用 C# 和 Dictionary 或 List 之类的关键字,但我已经像这样将 JObject 和 int 解析为一些。

@{
   int myvar = context.Variables['var'];
   return myvar > 5;
}

@((int)context.Variables('year') < 2022)

Api 管理为您提供“GetValueOrDefault<Type>('ParameterName', 'DefaultValueIfNull')”方法,让您捕获 header、变量或查询并直接解析,您会在这里找到它。

https://learn.microsoft.com/en-us/azure/api-management/api-management-policy-expressions

尝试将JArray的值解析为条件中的 JArray。

<policies>
<inbound>
    <base />
    <set-variable name="someList" value="[a,b,c,d]" />
    <when condition="@(JArray.Parse((string)context.Variables["someList"]).Contains("a"))">
    </when>
    <otherwise>
    </otherwise>
</inbound>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM