[英]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.