首页 > 解决方案 > 需要使用 Azure APIM set-body 策略修改响应

问题描述

我对 Azure APIM 比较陌生,我有这个后端,我可以调用它以格式返回响应

{
    "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."
    ]
}

标签: azureazure-api-management

解决方案


作为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>

注意:这种方法需要对您的响应数据格式进行高度规范。


推荐阅读