.Net 5 迁移时如何实现Strathweb同款自定义响应输出缓存功能
.NET 5 Web API自定义输出缓存实现方案
核心实现逻辑
直接使用ASP.NET Core官方提供的OutputCache中间件即可替代Strathweb.CacheOutput库的全部能力,自定义缓存键、覆盖默认缓存规则、服务端+客户端缓存的需求都可以原生支持,无需额外引入第三方库。
步骤1:自定义缓存键生成逻辑
实现IOutputCacheKeyProvider接口,替换原有继承DefaultCacheKeyGenerator的逻辑:
using Microsoft.AspNetCore.OutputCaching; using System.Security.Claims; public class CustomCacheKeyProvider : IOutputCacheKeyProvider { private const string ItemSeparator = "-"; private const string ParamSeparator = "="; public async ValueTask<string> CreateKeyAsync(OutputCacheContext context, CancellationToken cancellationToken) { // 获取默认生成的基础缓存键,已包含请求路径、媒体类型、查询参数等默认维度 var baseKey = await OutputCacheKeyProvider.Default.CreateKeyAsync(context, cancellationToken); // 追加自定义请求头维度 if (context.HttpContext.Request.Headers.TryGetValue("IsDR", out var isDrValue)) { baseKey += $"{ItemSeparator}isdr{ParamSeparator}{isDrValue}"; } // 追加Authorization中用户ID维度 if (context.HttpContext.User.Identity?.IsAuthenticated == true) { var userId = context.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value; if (!string.IsNullOrEmpty(userId)) { baseKey += $"{ItemSeparator}uid{ParamSeparator}{userId}"; } } return baseKey; } }
步骤2:配置缓存策略,覆盖默认规则
在Program.cs中注册缓存服务,明确允许带Authorization标头的请求参与缓存:
// 注册输出缓存服务 builder.Services.AddOutputCache(options => { // 自定义默认缓存策略 options.DefaultPolicy = new OutputCachePolicyBuilder() // 开启缓存 .Cache() // 默认按所有查询参数生成缓存键,和原有逻辑保持一致 .SetVaryByQuery("*") // 覆盖默认规则:允许认证请求缓存 .With(context => !context.HttpContext.Request.Headers.ContainsKey("Authorization") || context.HttpContext.User.Identity?.IsAuthenticated == true) // 配置客户端缓存过期时间,会自动写入Cache-Control响应头 .SetResponseExpiration(TimeSpan.FromMinutes(10)) .Build(); // 注册自定义缓存键生成器 options.KeyProvider = new CustomCacheKeyProvider(); }); // 注册Redis分布式缓存(原有Redis存储逻辑复用) builder.Services.AddStackExchangeRedisCache(options => { options.Configuration = "你的Redis连接配置"; options.InstanceName = "ApiCache:"; });
步骤3:启用中间件
在中间件管道中正确配置OutputCache,注意顺序必须在路由之后,授权之前:
app.UseRouting(); // 启用输出缓存 app.UseOutputCache(); app.UseAuthorization();
配置完成后,在需要缓存的接口上添加[OutputCache]特性即可生效,用法和原有Strathweb库的[CacheOutput]特性一致,也可以配置全局缓存规则覆盖所有接口。
是否需要改用Distributed Caching
不需要完全自己重新实现Distributed Caching的整套逻辑:
- 官方OutputCache中间件默认会优先使用你注册的
IDistributedCache实现作为缓存存储,你原有基于Redis的缓存方案可以直接复用,不需要修改存储逻辑 - 如果是单实例部署的场景,也可以默认使用内存缓存,无需额外配置分布式缓存,中间件会自动适配
- 服务端缓存的过期、淘汰、更新逻辑都由中间件原生处理,不需要自己额外实现缓存操作的封装
内容的提问来源于stack exchange,提问作者Lee Z
相关产品推荐
相关产品推荐

