需要使用 Azure APIM set-body 策略修改响应

Need to modify response using Azure APIM set-body policy

我对 Azure APIM 比较陌生,我有这个后端,我可以调用它 returns 格式为

的响应
{
    "data": {
        "attributes": {
            "municipalities": []
        }
    }
}

我想修改响应,使数据以

格式返回
{
    "data": {
            "municipalities": []
    }
}

我试过使用定体液模板

<outbound>
<set-body template="liquid">
   {
        "data": {
                "municipalities": {{body.data.attributes.municipalities}}
               }
    }</set-body>
</outbound>

但我得到的回应只是

{
    "data": {
        "municipalities":
    }
}

如果有人能指出我做错了什么或者是否有更好的方法来做到这一点?

我还尝试使用下面的代码来检查我是否能够检索“数据”属性,但我在 Azure APIM 测试的跟踪部分遇到了以下错误

<outbound>
    <set-body> 
    @{ 
        JObject inBody = context.Request.Body.As<JObject>();
        return inBody["data"].ToString(); 
    } 
    </set-body>
</outbound>

错误:

{
    "messages": [
        {
            "message": "Expression evaluation failed.",
            "expression": " \n    JObject inBody = context.Request.Body.As<JObject>();\n    return inBody[\"data\"].ToString(); \n",
            "details": "Object reference not set to an instance of an object."
        },
        "Expression evaluation failed. Object reference not set to an instance of an object.",
        "Object reference not set to an instance of an object."
    ]
}

由于body.data.attributes.municipalities是一个数组,所以不能直接写成"municipalities":。为了您修改json数据格式的要求,我们需要写每个数组项的每个属性。以下是我的步骤供大家参考。

我的json是:

{
    "data": {
        "attributes": {
            "municipalities": [
                {
                    "name": "hury",
                    "email": "hury@mail.com"
                },
                {
                    "name": "mike",
                    "email": "mike@email.com"
                }
            ]
        }
    }
}

而我的液体模板显示为:

================================更新==== ========================

首先您分享的代码JObject inBody = context.Request.Body.As<JObject>();无法获取响应数据。你应该使用 JObject inBody = context.Response.Body.As<JObject>();.

那么针对你的问题“有没有更简单的方法去掉.attributes部分,我在下面提供一个解决方案供你参考。

不要使用液体模板,使用Replace"attributes": {替换为空模板并使用Substring删除最后一个}

<set-body>@{ 
    JObject inBody = context.Response.Body.As<JObject>();
    string str = inBody.ToString();
    string str1 = str.Replace("\"attributes\": {", "");
    string result = str1.Substring(0, str1.Length-1);
    return result; 
}</set-body>

注意:此方法需要高度规范您的响应数据格式。

我也设法用下面的代码得到了想要的输出,所以代码是通用的,不需要做任何字符串操作。

<set-body>@{ 
    JToken inBody = context.Response.Body.As<JToken>()["data"]["attributes"];
    JObject jsonObject = new JObject{
    ["data"] = inBody
}; 
return jsonObject.ToString();
}</set-body>