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

如何在Azure APIM策略中提取JSON响应的status与code属性

Azure APIM策略提取error对象属性问题解决

原代码存在的问题

  • 响应流只能读取一次:context.Response.Body.As<JObject>()会消耗响应流,重复调用会导致后续读取无数据。
  • 错误的JSON解析:context.Response.Body.As<JObject>()["error"]已经是JObject类型,无需再用JObject.Parse(该方法用于解析JSON字符串)。
  • 变量名重复覆盖:两个<set-variable>使用同一个errorStatus变量名,第二个值会覆盖第一个,无法同时保存status和code。
  • 冗余类型转换:status是数字类型,无需先转字符串再转回int,直接存储int类型更高效。

修正后的策略代码

<policies>
    <inbound>
        <base />
    </inbound>
    <backend>
        <base />
    </backend>
    <outbound>
        <base />
        <!-- 缓存完整响应体,避免重复读取流耗尽 -->
        <set-variable name="fullResponse" value="@(context.Response.Body.As<JObject>())" />
        <choose>
            <when condition="@(context.Variables.GetValueOrDefault<JObject>("fullResponse")["error"] != null)">
                <!-- 提取并缓存error对象 -->
                <set-variable name="errorObj" value="@(context.Variables.GetValueOrDefault<JObject>("fullResponse")["error"])" />
                <!-- 提取status(数字类型) -->
                <set-variable name="errorStatus" value="@((int)context.Variables.GetValueOrDefault<JObject>("errorObj")["status"])" />
                <!-- 提取code(字符串类型) -->
                <set-variable name="errorCode" value="@((string)context.Variables.GetValueOrDefault<JObject>("errorObj")["code"])" />
                
                <choose>
                    <when condition="@((int)context.Variables["errorStatus"] == 404)">
                        <return-response>
                            <set-status code="200" reason="NotFound" />
                            <set-body template="liquid">
                                { 
                                    "status": "NotFound"
                                }
                            </set-body>
                        </return-response>
                    </when>
                </choose>
            </when>
        </choose>
    </outbound>
    <on-error>
        <base />
    </on-error>
</policies>

关键修改说明

  1. 缓存完整响应:新增fullResponse变量存储整个响应的JObject,确保响应流仅被读取一次,后续操作基于缓存对象执行。
  2. 复用error对象:新增errorObj变量缓存error节点,避免重复从完整响应中查找属性,提升策略执行效率。
  3. 修正变量与类型:分别用errorStatus(int类型)和errorCode(string类型)存储对应属性,解决变量覆盖问题。
  4. 移除错误解析:直接通过JObject索引访问属性,删除多余的JObject.Parse调用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 09:20:37