Skip to content

Instantly share code, notes, and snippets.

@jochenvw
Created August 4, 2020 11:10
Show Gist options
  • Save jochenvw/2ed51085b5f77f2b18da3a2b9fb61ffb to your computer and use it in GitHub Desktop.
Save jochenvw/2ed51085b5f77f2b18da3a2b9fb61ffb to your computer and use it in GitHub Desktop.
<!-- Custom caching policy for on HTTP POST for Azure API Management:
1. Policy looks in the Request body - 'cacheKey' property which then used as cache key.
Expected values are: <null>, ALL or NOEXPIRED
Defaults to ALL in case <null>
2. Cache expiration set to 60 seconds/1 minute
!-->
<policies>
<inbound>
<base />
<!-- CACHING: checks for cacheKey property in message body !-->
<set-variable name="cacheKey" value="@(context.Request.Body?.As<JObject>(preserveContent: true)["cacheKey"]?.ToString() ?? "ALL")" />
<cache-lookup-value key="@((string)context.Variables["cacheKey"])" variable-name="cachedResponseValue" />
<choose>
<when condition="@(context.Variables.ContainsKey("cachedResponseValue"))">
<return-response>
<set-header name="Content-Type" exists-action="override">application/json</set-header>
<set-body>@((string)context.Variables["cachedResponseValue"])</set-body>
</return-response>
</when>
</choose>
</inbound>
<backend>
<base />
</backend>
<outbound>
<base />
<set-variable name="responseValue" value="@(context.Response.Body.As<string>(preserveContent: true))" />
<cache-store-value key="@((string)context.Variables["cacheKey"])" value="@((string)context.Variables["responseValue"])" duration="60" />
</outbound>
<on-error>
<base />
</on-error>
</policies>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment