![](/img/trans.png)
[英]Convert response body from XML to Json in API Management Policy Expression when forwarding response to different URL
[英]Azure API policy JSON conversion while returning the response from cache
我正在使用以下策略代碼並將數據存儲在緩存中。 在存儲為字符串時,它工作正常,但要求是以 JSON 格式存儲,並且在轉換過程中失敗並拋出錯誤。
<policies>
<inbound>
<base />
<set-variable name="cacheKey" value="@(context.Request.MatchedParameters["flightno"])" />
<cache-lookup-value key="@((string)context.Variables["cacheKey"])" variable-name="cachedResponseValue" />
<set-variable name="FinalResponse" value="@((JObject)context.Variables["cachedResponseValue"])" />
<choose>
<when condition="@(context.Variables.ContainsKey("cachedResponseValue"))">
<!-- If found in cache then get it from the cache and retun -->
<return-response>
<set-body>@((JObject)context.Variables["FinalResponse"])</set-body>
</return-response>
</when>
</choose>
</inbound>
<backend>
<base />
</backend>
<outbound>
<base />
<set-variable name="responseValue" value="@(context.Response.Body.As<JObject>(preserveContent: true))" />
<!-- Store result in cache -->
<cache-store-value key="@("" + context.Variables["cacheKey"])" value="@((JObject)context.Variables["responseValue"])" duration="30" />
</outbound>
<on-error>
<base />
</on-error>
</policies>
我能夠將有效負載作為 json 存儲在緩存中,在檢索時,我想返回 json 並嘗試解析它。 將標簽中的響應解析為以下語法時出現錯誤
<set-body>@((JObject)context.Variables["FinalResponse"])</set-body>
Error in element 'set-body' on line 22, column 22: Expression return type 'Newtonsoft.Json.Linq.JObject' is not allowed.
它工作正常,如果響應數據類型保持為字符串
<set-body>@((string)context.Variables["FinalResponse"])</set-body>
您知道如何將響應正文轉換為 json 嗎?
這是不允許的,因為 set-body 策略只接受字符串或字節數組內容。 簡單的解決方案是將 JObject 轉換為字符串:
<return-response>
<set-header name="Content-Type">
<value>application/json</value>
</set-header>
<set-body>@(((JObject)context.Variables["FinalResponse"]).ToString())</set-body>
</return-response>
響應仍然是有效的 JSON 和 with。 上面set-header
不會影響 body 的處理方式,但您需要它來響應讓客戶了解您正在傳遞 JSON。
這里唯一的事情是:
很多時間都花在序列化和反序列化響應上而沒有任何好處。 如果您的策略的其他部分不需要將響應作為 JObject 進行處理,則一種更簡單、更快捷的方法是將其簡單地存儲為字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.