我试图弄清楚如何在 Azure APIM 策略编辑器中正确使用 XML 到 JSON 的转换。我见过几十个例子,其中所有的都是这样的:
<xml-to-json kind="direct" apply="always" consider-accept-header="false" />
但是,我无法在我的政策中找到合适的位置来放置代码以使其达到我的预期。这是我的出站策略,我希望在其中使用它:
<outbound>
<base />
<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))" />
<!-- Error response as per https://github.com/Microsoft/api-guidelines/blob/master/Guidelines.md#7102-error-condition-responses -->
<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>
<xml-to-json kind="direct" apply="always" consider-accept-header="false" />
</outbound>
如您所见,我尝试将转换线放在出站策略的最后,但它没有达到我的预期;我仍然返回了一个 xml 文档。
在了解如何修改我的政策以发挥作用的任何帮助都会很棒。