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

Azure APIM出站策略配置xml-to-json转换后仍返回XML问题咨询

故障原因与修改方案

核心问题

你的策略执行顺序配置错误,这是转换不生效的根本原因:

  • xml-to-json 策略的作用是将当前的XML格式响应体转换为JSON格式,必须放在所有读取、修改响应体的策略之前执行
  • 你之前将转换语句放在出站策略末尾,此时前面的set-body、变量读取逻辑已经完成了响应体的修改,要么响应体已经不是XML格式,要么转换结果会覆盖之前的自定义逻辑,自然无法得到预期效果

修改后的出站策略

<outbound>
    <base />
    <!-- 第一步:先转换后端返回的原始XML为JSON,放在所有响应体操作逻辑最前面 -->
    <xml-to-json kind="direct" apply="always" consider-accept-header="false" />
    <choose>
        <when condition="@(context.Response.StatusCode < 400)">
            <set-body template="liquid">
            {% if body.envelope.body.GetProjectsByQueryResponse.GetProjectsByQueryResult %}"{{body.envelope.body.GetProjectsByQueryResponse.GetProjectsByQueryResult | Replace: '\r', '\r' | Replace: '\n', '\n' | Replace: '([^\\](\\\\)*)"', '$1\"'}}{% else %} null {% endif %}
            </set-body>
        </when>
        <otherwise>
            <set-variable name="old-body" value="@(context.Response.Body.As<string>(preserveContent: true))" />
            <set-body template="liquid">{
        "error": {
            "code": "{{body.envelope.body.fault.faultcode}}",
            "message": "{{body.envelope.body.fault.faultstring}}"
        }
    }
    </set-body>
            <choose>
                <when condition="@(string.IsNullOrEmpty(context.Response.Body.As<JObject>(preserveContent: true)["error"]["code"].ToString()) && string.IsNullOrEmpty(context.Response.Body.As<JObject>(preserveContent: true)["error"]["message"].ToString()))">
                    <set-body>@{
                var newResponseBody = new JObject();
                newResponseBody["error"] = new JObject();
                newResponseBody["error"]["code"] = "InvalidErrorResponseBody";
                if (string.IsNullOrEmpty((string)context.Variables["old-body"]))
                {
                    newResponseBody["error"]["message"] = "The error response body was not a valid SOAP error response. The response body was empty.";
                }
                else
                {
                    newResponseBody["error"]["message"] = "The error response body was not a valid SOAP error response. The response body was: '" + context.Variables["old-body"] + "'.";
                }
                return newResponseBody.ToString();
            }</set-body>
                </when>
            </choose>
        </otherwise>
    </choose>
    <set-header name="Content-Type" exists-action="override">
        <value>application/json</value>
    </set-header>
</outbound>

补充优化建议

如果你的后端返回的是标准SOAP 1.1/1.2协议内容,可以将xml-to-json的kind属性改为soap,转换时会自动过滤SOAP信封的外层节点,直接返回body内的业务数据,后续liquid的取值逻辑可以简化,不需要再加body.envelope.body前缀。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 07:27:04