azure - 需要使用 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."
]
}
解决方案
作为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>
注意:这种方法需要对您的响应数据格式进行高度规范。
推荐阅读
- node.js - 如何模拟模块函数,以便在代码中的某处调用时引发异常
- .htaccess - 可以重定向子域,但不能重定向子域的 slug
- r - 计算 R 中缺失值的数量
- android - 我可以使用意图从谷歌地图中检索 lat-lng
- ruby-on-rails - 对于我添加了参数的 sidekiq 方法,我收到“ArgumentError: wrong number of arguments”。有什么理由会这样吗?
- javascript - 对象不工作的 JsDoc 联合类型
- javascript - 尝试启动 react 和 nodejs 时出现 NPM 错误
- php - Laravel如何在where条件下获取所有值
- android - kotlin 中的泛型、伴生对象和继承
- python - 熊猫将值分配给数据框,以另一个具有相同维度问题/问题的值为条件