如何在 Azure API 管理中的设置变量策略中访问请求正文?

问题描述 投票:0回答:2

json 请求正文包含一个我想要访问并存储在上下文中的值。变量,因此稍后我可以在控制流表达式中使用它。

这是 json 请求正文:

  {
    "File": [
      {
        "Key": "ValueToGet",
        "List": [
          {},
          {}
        ]
      }
    ]
  }

我希望“ValueToGet”成为设置变量策略的值,如下所示:

<set-variable name="myVar" value="ValueToGet">

我尝试使用以下表达式将主体存储在单独的变量中:

<set-variable name="varBody" value="@(context.Request.Body.As<JObject>())" />

然后在下一个设置变量策略中使用它:

<set-variable name="myVar" value="@{
        JObject json = JObject.Parse(context.Variables.GetValueOrDefault<string>("varBody"));
        var code = json.GetValue("Key");
        return code;
        }" />

但它似乎不起作用,我收到以下错误,该错误与我存储身体的方式有关:

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

当我尝试在相同的设置变量策略中访问请求正文时,出现相同的错误。

我已经为这个问题苦苦挣扎有一段时间了,非常感谢任何帮助。谢谢你。

c# json azure azure-api-management
2个回答
2
投票

如果您只想使用第一个

Key
项的
File
的值设置一个变量,只需尝试以下表达式:

<set-variable name="myVar" value="@(context.Request.Body.As<JObject>()["File"][0]["Key"])" />

我已经用您的请求主体进行了测试,它非常适合我:

跟踪日志:


-1
投票

您的以下问题得到解决了吗:

感谢您的关注。我会接受答案,因为这是我想要的。现在的问题是该变量的类型为 JValue,当我尝试访问它时 - 我收到类型错误:“表达式求值失败。无法将 Newtonsoft.Json.Linq.JValue 类型的上下文变量 myVar 转换为

© www.soinside.com 2019 - 2024. All rights reserved.