如何在 Azure API 管理中访问 set-variable 策略中的请求 body?
How can I access request body in set-variable policy in Azure API Management?
json 请求 body 包含一个我想要访问并存储在 context.Variable 中的值,因此稍后我可以在控制流表达式中使用它。
这里是 json 请求 body:
{
"File": [
{
"Key": "ValueToGet",
"List": [
{},
{}
]
}
]
}
我希望“ValueToGet”成为 set-variable 策略的值,如下所示:
<set-variable name="myVar" value="ValueToGet">
我试过用这个表达式将 body 存储在一个单独的变量中:
<set-variable name="varBody" value="@(context.Request.Body.As<JObject>())" />
并稍后在下一个 set-variable 政策中使用它:
<set-variable name="myVar" value="@{
JObject json = JObject.Parse(context.Variables.GetValueOrDefault<string>("varBody"));
var code = json.GetValue("Key");
return code;
}" />
但它似乎不起作用,我收到以下与我存储 body 的方式有关的错误:
{
"messages": [
{
"message": "Expression evaluation failed.",
"expression": "context.Request.Body.As<JObject>()",
"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."
]
}
当我尝试访问同一 set-variable 策略中的请求的 body 时,我遇到了同样的错误。
我已经为这个问题苦苦思索了很长一段时间,如果有任何帮助,我将不胜感激。谢谢。
如果您只想设置第一个 File
项的值为 Key
的变量,只需尝试以下表达式:
<set-variable name="myVar" value="@(context.Request.Body.As<JObject>()["File"][0]["Key"])" />
我已经对你的请求正文进行了测试,它非常适合我:
跟踪日志:
json 请求 body 包含一个我想要访问并存储在 context.Variable 中的值,因此稍后我可以在控制流表达式中使用它。
这里是 json 请求 body:
{
"File": [
{
"Key": "ValueToGet",
"List": [
{},
{}
]
}
]
}
我希望“ValueToGet”成为 set-variable 策略的值,如下所示:
<set-variable name="myVar" value="ValueToGet">
我试过用这个表达式将 body 存储在一个单独的变量中:
<set-variable name="varBody" value="@(context.Request.Body.As<JObject>())" />
并稍后在下一个 set-variable 政策中使用它:
<set-variable name="myVar" value="@{
JObject json = JObject.Parse(context.Variables.GetValueOrDefault<string>("varBody"));
var code = json.GetValue("Key");
return code;
}" />
但它似乎不起作用,我收到以下与我存储 body 的方式有关的错误:
{
"messages": [
{
"message": "Expression evaluation failed.",
"expression": "context.Request.Body.As<JObject>()",
"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."
]
}
当我尝试访问同一 set-variable 策略中的请求的 body 时,我遇到了同样的错误。
我已经为这个问题苦苦思索了很长一段时间,如果有任何帮助,我将不胜感激。谢谢。
如果您只想设置第一个 File
项的值为 Key
的变量,只需尝试以下表达式:
<set-variable name="myVar" value="@(context.Request.Body.As<JObject>()["File"][0]["Key"])" />
我已经对你的请求正文进行了测试,它非常适合我:
跟踪日志: