简体   繁体   中英

How can I access request body in set-variable policy in Azure API Management?

The json request body contains a value that I want to access and store in a context.Variable, so later on I can use it in a control flow expression.

Here is the json request body:

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

I want the "ValueToGet" to be the value of the set-variable policy like so:

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

I have tried storing the body in a separate variable with this expression:

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

and later using it in the next set-variable policy:

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

But it does not seem to work and I am receiving the following error that is connected to the way that I'm storing my 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."
    ]
}

I get the same error when I'm trying to access the body of the request in the same set-variable policy.

I've been banging my head against this problem for quite a while and I'd appreciate any help. Thank you.

If you just want to set a variable with the value of Key of first File item, just try the expression below:

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

I have tested on my side with your request body and it works perfectly for me:

在此处输入图像描述

Trace Log:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM