设置响应缓存持续时间Set response cache duration
本文介绍 Azure API 管理策略示例,该示例演示如何使用后端发送的 Cache-Control 标头中的 maxAge 值设置响应缓存持续时间。This article shows an Azure API management policy sample that demonstrates how to set response cache duration using maxAge value in Cache-Control header sent by the backend. 若要设置或编辑策略代码,请执行设置或编辑策略中所述的步骤。To set or edit a policy code, follow the steps described in Set or edit a policy. 若要查看其他示例,请参阅策略示例。To see other examples, see policy samples.
策略Policy
将代码粘贴到“入站”块中 。Paste the code into the inbound block.
<!-- This snippet demonstrates how to set response cache duration using maxAge value in Cache-Control header sent by the backend. -->
<!-- Copy the following snippet into the outbound section. -->
<policies>
<inbound>
<base />
</inbound>
<backend>
<base />
</backend>
<outbound>
<base />
<!-- The following policy can be tested by setting up an API and operation mapped to GET http://httpbin.org/cache/{duration} -->
<cache-store duration="@{
var header = context.Response.Headers.GetValueOrDefault("Cache-Control","");
var maxAge = Regex.Match(header, @"max-age=(?<maxAge>\d+)").Groups["maxAge"]?.Value;
return (!string.IsNullOrEmpty(maxAge))?int.Parse(maxAge):300;
}"
/>
</outbound>
<on-error>
<base />
</on-error>
</policies>
后续步骤Next steps
了解有关 APIM 策略的详细信息:Learn more about APIM policies: