如何使用 Azure API 管理器缓存存储值策略存储 JSON 负载?

How to store JSON Payload using Azure API Manager cache-store-value policy?

美好的一天,

我正在尝试使用 "cache-store-value" 策略将传入的 JSON 有效负载存储到 Azure API Manager 内部缓存中。密钥将是有效负载中的字段之一。我能够提取密钥,但是当我尝试存储有效负载时出现错误

"Expression evaluation failed. Object reference not set to an instance of an object."

这是我正在编写的代码

<policies>
<inbound>
    <base />
    <set-variable name="processIdKey" value="@((string)context.Request.Body.As<JObject>()["id"])" />
    <set-variable name="validationResults" value="@(context.Request.Body.As<JObject>())" />
    <cache-store-value key="@((string)context.Variables["processIdKey"])" value="@((string)context.Variables["validationResults"])" duration="30" />
</inbound>
<backend>
    <base />
</backend>
<outbound>
    <base />
</outbound>
<on-error>
    <base />
</on-error>

我稍后需要在 api 的另一个方法中提取值,因此需要知道如何将 JSON 有效载荷存储在缓存中并提取相同的值以作为响应发送到另一个方法。

在此先感谢您的帮助。

尝试context.Request.Body.As<string>()。 Method As 当前支持以下类型作为通用参数值:

byte[]
string
JToken
JObject
JArray
XNode
XElement
XDocument

请注意,如果您尝试调用 .As<JObject> 而不是 不包含有效 JSON 的响应,您将得到一个异常,这同样适用于其他类型还有。

这里是关于缓存的article你可以参考。

我找到了答案,问题是,我们不能在整个代理中多次提取 context.Request 对象。所以我必须做的是将它作为 JObject 存储在一个变量中,然后从中提取 "id" 字段。稍后将其转换为字符串以存储在缓存中。这是更新的代码。

<policies>
<inbound>
    <base />
    <set-variable name="validationResults" value="@(context.Request.Body.As<JObject>())" />
    <set-variable name="processIdKey" value="@((string)((JObject)context.Variables["validationResults"])["id"])" />
    <set-variable name="payload" value="@((string)((JObject)context.Variables["validationResults"]).ToString())" />
    <cache-store-value key="@((string)context.Variables["processIdKey"])" value="@((string)context.Variables["payload"])" duration="30" />
</inbound>
<backend>
    <base />
</backend>
<outbound>
    <base />
</outbound>
<on-error>
    <base />
</on-error>

希望对您有所帮助。谢谢