簡體   English   中英

Azure API 策略 JSON 轉換同時從緩存返回響應

[英]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。

這里唯一的事情是:

  1. 調用后端並將響應解析為 JObject
  2. JObject 存入緩存,將被序列化
  3. JObject 從緩存中讀取,將被反序列化
  4. JObject 被放入響應,將被序列化為字符串

很多時間都花在序列化和反序列化響應上而沒有任何好處。 如果您的策略的其他部分不需要將響應作為 JObject 進行處理,則一種更簡單、更快捷的方法是將其簡單地存儲為字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM