Skip to content

Instantly share code, notes, and snippets.

@jpolvora
Forked from jochenvw/HTTPPostCachingPolicy.xml
Created April 20, 2021 19:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jpolvora/ea17ea49789e180150ab99e813db6b3b to your computer and use it in GitHub Desktop.
Save jpolvora/ea17ea49789e180150ab99e813db6b3b 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