入站策略自定义认证的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
相关产品推荐
相关产品推荐

