You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

入站策略自定义认证的when condition异常,请求排查方案

问题解决:API Management入站策略自定义认证When Condition判断500错误

错误原因

你遇到的500内部错误,是因为错误地将send-request返回的authResponse变量当作JSON对象(JObject)处理,实际上该变量是IResponse类型的响应对象,直接强转JObject会触发类型转换异常。另外你尝试的context.Variables["authResponse.StatusCode"]写法也不对——这是在查找名为authResponse.StatusCode的变量,而非authResponse对象的StatusCode属性,会返回null导致转换错误。

正确写法

写法一:显式转换为IResponse后访问属性

<choose>
    <when condition="@(((IResponse)context.Variables["authResponse"]).StatusCode == 200)">
        <!-- Continue with the API call -->
    </when>
    <otherwise>
        <return-response>
            <set-status code="401" reason="Unauthorized" />
            <set-header name="Content-Type" exists-action="override">
                <value>application/json</value>
            </set-header>
            <set-body>
                {
                    "errorMessage": "Authentication failed"
                }
            </set-body>
        </return-response>
    </otherwise>
</choose>

写法二:简化属性访问语法(API Management支持直接点访问)

<choose>
    <when condition="@((int)context.Variables["authResponse"].StatusCode == 200)">
        <!-- Continue with the API call -->
    </when>
    <otherwise>
        <!-- 同上面的返回响应逻辑 -->
    </otherwise>
</choose>

排查技巧

如果后续遇到类似变量类型问题,可以在send-request后添加trace策略输出变量信息,方便调试:

<trace source="AuthDebug" severity="information">
    <message>authResponse类型: @(context.Variables["authResponse"].GetType().FullName)</message>
    <message>响应状态码: @(((IResponse)context.Variables["authResponse"]).StatusCode)</message>
</trace>

内容的提问来源于stack exchange,提问作者BLNT

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 00:20:40