当它抛出错误时如何检查策略变量中的 null - 索引超出数组的范围

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

有时,我在“响应”中有超过 2 个用管道符号分隔的值,而其他时候,我只得到 2 个值,在这种情况下,下面的行抛出索引超出范围错误

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

当我使用变量值将某些内容检查到 Choose When 条件中时,如下所示,它会抛出错误,因为它试图评估上面的行。

错误是 - 索引超出了数组的范围。

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

我在策略和跟踪中有这条线,我发现如果响应中没有第三个值并导致索引超出范围,它就会失败。如何调整它,好像什么都没有,然后只是空字符串,即“”值?

编辑

我正在寻找类似空检查的东西,就像在 C# 中我们有“?”如果为空,则放入一些空字符串。如何实现?

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

您可以使用下面的代码来判断数组(拆分字符串得到的)是否有两个以上的变量。

<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>

或者如果您的要求是获取该字符串中 | 之后的最后一个值,您可以直接使用一行。

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