You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core 6中Cache.NoSlidingExpiration的正确用法求助

.NET Core Razor Pages 中替代 WebForms Cache.NoSlidingExpiration 的实现方式

在 ASP.NET WebForms 中,Cache.NoSlidingExpiration 用于指定缓存项不使用滑动过期策略——即缓存项不会因被访问而延长有效期,仅遵循绝对过期时间(若设置)。在 .NET Core 的 IMemoryCache 中,没有直接对应的静态字段,需通过配置 MemoryCacheEntryOptions 来实现相同效果。

正确实现步骤

  1. 注册 IMemoryCache 服务
    在 Program.cs(.NET 6+)中先注册缓存服务:

    var builder = WebApplication.CreateBuilder(args);
    builder.Services.AddMemoryCache(); // 注册内存缓存服务
    builder.Services.AddRazorPages();
    // ... 其他配置 ...
    
  2. 构造函数注入 IMemoryCache
    在 Razor Page 的后台模型中注入缓存实例:

    public class YourPageModel : PageModel
    {
        private readonly IMemoryCache _cache;
    
        public YourPageModel(IMemoryCache cache)
        {
            _cache = cache;
        }
    
        // ... Page 方法 ...
    }
    
  3. 配置缓存选项(禁用滑动过期)
    通过 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 15:57:13