Background : I am defining an API in Azure API Management. I have defined a policy on "All operations" level. This policy does a couple of things. One of the things it does is setting a variable in the context object, so I can re-use the variable in when condition.
What I need help with:
How can I define a list in Azure API-M policy, which I can refer to in when condition?
Code example :
All operations policy:
<policies>
<inbound>
<base />
<set-variable name="someList" value="[a,b,c,d]" />
<when condition="@(context.Variables["someList"].Contains("a"))"
</when>
<otherwise>
</otherwise>
</inbound>
</policies>
It seems that my issue is that the variable "someList" is not recognized as an array, but as a String = "[a,b,c,d]". So basically, it will return true if the condition would say Contains("[").
I have also tried to store value as named values, but named values can't contain a Array as value.
What I want to achieve is keeping a list of subscriptions, so that I can match incoming subscription key in request to a list of pre-defined subscription keys.
Try parsing the context.Variables['somelist'] as a list before using.ContainsKey('key'). I never needed to parse a list, so you have to google it how to do it, use keywords like C# and Dictionary or List for this, but i've done some parsing as JObject and int like this.
@{
int myvar = context.Variables['var'];
return myvar > 5;
}
And
@((int)context.Variables('year') < 2022)
Api management offers you the "GetValueOrDefault<Type>('ParameterName', 'DefaultValueIfNull')" method to let you capture a header, variable or query and parse it directly, you'll find it here.
https://learn.microsoft.com/en-us/azure/api-management/api-management-policy-expressions
Try parsing the value of someList to JArray
in the condition.
<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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.