.NET Core 6中Cache.NoSlidingExpiration的正确用法求助
.NET Core Razor Pages 中替代 WebForms Cache.NoSlidingExpiration 的实现方式
在 ASP.NET WebForms 中,Cache.NoSlidingExpiration 用于指定缓存项不使用滑动过期策略——即缓存项不会因被访问而延长有效期,仅遵循绝对过期时间(若设置)。在 .NET Core 的 IMemoryCache 中,没有直接对应的静态字段,需通过配置 MemoryCacheEntryOptions 来实现相同效果。
正确实现步骤
注册 IMemoryCache 服务
在Program.cs(.NET 6+)中先注册缓存服务:var builder = WebApplication.CreateBuilder(args); builder.Services.AddMemoryCache(); // 注册内存缓存服务 builder.Services.AddRazorPages(); // ... 其他配置 ...构造函数注入 IMemoryCache
在 Razor Page 的后台模型中注入缓存实例:public class YourPageModel : PageModel { private readonly IMemoryCache _cache; public YourPageModel(IMemoryCache cache) { _cache = cache; } // ... Page 方法 ... }配置缓存选项(禁用滑动过期)
通过MemoryCacheEntryOptions配置缓存规则,不设置SlidingExpiration属性即等同于 WebForms 的Cache.NoSlidingExpiration:public void OnGet() { // 示例:添加缓存项,1小时后绝对过期,禁用滑动过期 var cacheOptions = new MemoryCacheEntryOptions { // 设置绝对过期时间 AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1), // 不设置 SlidingExpiration,即禁用滑动过期 Priority = CacheItemPriority.Normal }; _cache.Set("CachedKey", "YourCachedValue", cacheOptions); // 若需缓存项永不过期(不推荐,易引发内存泄漏) var permanentCacheOptions = new MemoryCacheEntryOptions { AbsoluteExpiration = DateTimeOffset.MaxValue, Priority = CacheItemPriority.NeverRemove }; _cache.Set("PermanentKey", "PermanentValue", permanentCacheOptions); }
常见问题排查
- 若之前使用
IMemoryCache失败,可能是未正确注册缓存服务,或错误设置了SlidingExpiration属性。 - 注意:
IMemoryCache是内存级缓存,重启应用后缓存会清空,若需持久化缓存可考虑分布式缓存(如 IDistributedCache)。
内容的提问来源于stack exchange,提问作者P.Parikh
相关产品推荐
相关产品推荐

