【问题标题】:OutputCache / ResponseCache VaryByParamOutputCache / ResponseCache VaryByParam
【发布时间】:2016-01-27 03:00:39
【问题描述】:

ResponseCache 在某种程度上替代了OutputCache;但是,我想做服务器端缓存以及每个参数输入。

根据herehere 的一些答案,我应该使用IMemoryCacheIDistributedCache 来执行此操作。我对在参数不同的控制器上缓存特别感兴趣,以前在 asp.net 4 中使用OutputCacheVaryByParam 完成,如下所示:

[OutputCache(CacheProfile = "Medium", VaryByParam = "id", Location = OutputCacheLocation.Server)]
public ActionResult Index(long id) 
{ 
    ///...
}

我将如何在 asp.net core 中复制它?

【问题讨论】:

  • 你解决了吗?

标签: c# asp.net-web-api asp.net-caching asp.net-core-1.0


【解决方案1】:

首先确保您使用的是 ASP.NET Core 1.1 或更高版本。

然后在你的控制器方法上使用类似的代码:

[ResponseCache(Duration = 300, VaryByQueryKeys = new string[] { "date_ref" } )]
public IActionResult Quality(DateTime date_ref)

来源:https://docs.microsoft.com/en-us/aspnet/core/performance/caching/middleware

【讨论】:

    【解决方案2】:

    如果你想通过控制器中所有请求中的所有请求查询参数来改变缓存:

    [ResponseCache(Duration = 20, VaryByQueryKeys = new[] { "*" })]
    public class ActiveSectionController : ControllerBase
    {
       //...
    }
    

    【讨论】:

      【解决方案3】:

      对于正在寻找答案的人...毕竟有 IMemoryCache 但不像过去那样漂亮 ActionFilterAttribute 但具有更大的灵活性。
      长话短说(对于 .Net core 2.1,主要由 Microsoft 文档 + 我理解):
      1- 在Startup.cs 文件中添加services.AddMemoryCache(); 服务到ConfigureServices
      2-将服务注入您的控制器:

      public class HomeController : Controller
      {
        private IMemoryCache _cache;
      
        public HomeController(IMemoryCache memoryCache)
        {
            _cache = memoryCache;
        }
      

      3- 任意(为了防止拼写错误)声明一个包含一堆键名的静态类:

      public static class CacheKeys
      {
        public static string SomeKey { get { return "someKey"; } }
        public static string AnotherKey { get { return "anotherKey"; } }
        ... list could be goes on based on your needs ...
      

      我更喜欢声明enum
      public enum CacheKeys { someKey, anotherKey, ...}
      3- 在 actionMethods 中使用它:
      获取缓存值:_cache.TryGetValue(CacheKeys.SomeKey, out someValue)
      或者如果 TryGetValue 失败则重置值:

      _cache.Set(CacheKeys.SomeKey, 
                 newCachableValue, 
                 new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromSeconds(60)));  
      

      结束。

      【讨论】:

        【解决方案4】:

        在 asp.net core 中使用它

        [ResponseCache(CacheProfileName = "TelegraphCache", VaryByQueryKeys = new[] { "id" })]
        

        【讨论】:

        • 但这不是在服务器上部署时缓存。请求 1 -> 响应时间 5 秒 请求 2 -> 响应时间也是 5 秒,但它返回 Age 和缓存控制 max age 在服务器上部署时缺少任何东西。请帮忙
        猜你喜欢
        • 2012-06-22
        • 2011-02-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-03-23
        • 2013-09-01
        相关资源
        最近更新 更多