Search code examples
.netazuremicroservicesazure-api-managementstring-conversion

How to check for null in variable in policy as it throw error - Index was outside the bounds of the array


At times, I have more than 2 values separated by pipe symbol in the "response" while some other times, I get only 2 value, in which case, the line below threw index out of range error

  <set-variable name="id" value="@(((String)context.Variables["response"]).Split('|')[2])" />

And when I am using the variable value to check something into the Choose When condition like below, it throws error as no value as it is trying to evaluate the above line.

Error is - Index was outside the bounds of the array.

<when condition="@((String)context.Variables["id"] == "Lollypop")">

I am having this line in policy and in trace, I see it fails if there is no 3rd value in response and resulting in index out of range. How to tweak this so as if nothing, then just empty string i.e "" value?

EDIT

I am looking for something like null check here like in C# we have "?" and if null, then put some empty string. How to achieve that?

@(((String)context.Variables["response"])?.Split('|')[2])


Solution

  • You can use the code below to judge if the array(which get from split the string) has more than two variables.

    <set-variable name="count" value="@(((String)context.Variables["response"]).Split('|').Count())" />
    <choose>
        <when condition="@((int)context.Variables["count"] > 2)">
            <set-variable name="id" value="@(((String)context.Variables["response"]).Split('|')[2])" />
        </when>
        <otherwise>
            <set-variable name="id" value="" />
        </otherwise>
    </choose>
    

    Or if your requirement is to get last value after | in that string, you can just use one line directly.

    <set-variable name="id" value="@(((String)context.Variables["response"]).Split('|').Last())" />