如何在Cloudflare中缓存.NET Core API的响应?
实现仅在Cloudflare中缓存.NET Core API响应的方案
要实现仅让Cloudflare缓存API响应、禁止浏览器缓存,核心是通过HTTP缓存头区分共享缓存(CDN)和客户端缓存:利用s-maxage指定Cloudflare的缓存时长,同时用max-age=0让浏览器不缓存。以下是具体实现方式:
方法1:手动设置响应头(适合单个操作)
直接在控制器操作中覆盖Cache-Control头,替代原有的[ResponseCache]特性:
[HttpGet] public IActionResult GetCachedData() { // 设置缓存规则:s-maxage给Cloudflare缓存120秒,max-age=0让浏览器不缓存 Response.Headers.CacheControl = "public, max-age=0, s-maxage=120"; // 你的业务逻辑 return Ok(new { content = "仅Cloudflare缓存的内容" }); }
方法2:自定义缓存特性(适合批量复用)
创建自定义ActionFilterAttribute,统一处理缓存头设置,避免重复代码:
public class CloudflareOnlyCacheAttribute : ActionFilterAttribute { private readonly int _cdnCacheDuration; public CloudflareOnlyCacheAttribute(int cdnCacheDuration) { _cdnCacheDuration = cdnCacheDuration; } public override void OnResultExecuting(ResultExecutingContext context) { // 生成目标缓存头 context.HttpContext.Response.Headers.CacheControl = $"public, max-age=0, s-maxage={_cdnCacheDuration}"; base.OnResultExecuting(context); } }
在控制器操作中使用该特性:
[HttpGet] [CloudflareOnlyCache(120)] // Cloudflare缓存120秒 public IActionResult GetCachedData() { return Ok(new { content = "仅Cloudflare缓存的内容" }); }
方法3:使用缓存配置文件(适合全局统一配置)
在Program.cs中配置全局缓存规则,通过CacheProfile复用设置:
builder.Services.AddControllers(options => { options.CacheProfiles.Add("CloudflareOnly", new CacheProfile { Location = ResponseCacheLocation.Public, Duration = 0, // 对应max-age=0,禁止浏览器缓存 CacheControlHeader = "public, max-age=0, s-maxage=120" // 明确指定完整缓存规则 }); });
在控制器操作中引用该配置:
[HttpGet] [ResponseCache(CacheProfileName = "CloudflareOnly")] public IActionResult GetCachedData() { return Ok(new { content = "仅Cloudflare缓存的内容" }); }
关键原理说明
s-maxage:仅对**共享缓存(如Cloudflare、代理服务器)**生效,指定其缓存时长;浏览器会忽略该参数。max-age=0:强制浏览器每次都向服务器发起请求,不会本地缓存响应。- 需移除原有的
[ResponseCache(Duration = 120, Location = ResponseCacheLocation.Any)]特性,避免默认生成的Cache-Control头冲突。
内容的提问来源于stack exchange,提问作者user23507681
相关产品推荐
相关产品推荐

