1
votes

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.

1
Thanks for checking in. I'll accept the answer, as it is what I wanted. The problem now is that the variable is of type JValue and when I'm trying to access it - I get type error: "Expression evaluation failed. Unable to convert context variable myVar of type Newtonsoft.Json.Linq.JValue to the type of `System.String.". Any idea on how to deal with this?Noobydee

1 Answers

1
votes

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:

enter image description here

Trace Log:

enter image description here