12

ResponseCache有点替代OutputCache; 但是,我想做服务器端缓存以及每个参数输入。

根据此处此处的一些答案,我应该使用IMemoryCacheIDistributedCache执行此操作。我对在参数不同的控制器上缓存特别感兴趣,以前在 asp.net 4 中使用OutputCacheVaryByParam类似这样:

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

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

4

4 回答 4

8

首先确保您使用的是 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

于 2017-06-13T16:42:56.500 回答
8

如果要通过控制器中所有请求中的所有请求查询参数更改缓存:

[ResponseCache(Duration = 20, VaryByQueryKeys = new[] { "*" })]
public class ActiveSectionController : ControllerBase
{
   //...
}
于 2019-11-22T09:12:58.543 回答
2

在 asp.net 核心中使用它

[ResponseCache(CacheProfileName = "TelegraphCache", VaryByQueryKeys = new[] { "id" })]
于 2019-12-04T08:45:26.843 回答
2

对于正在寻找答案的人......毕竟有IMemoryCache但不像过去那么漂亮ActionFilterAttribute但具有更大的灵活性。
长话短说(对于.Net core 2.1,主要由微软文档+我理解):
1-将services.AddMemoryCache();服务添加到ConfigureServices文件中Startup.cs
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)));  

结尾。

于 2018-08-28T15:08:53.470 回答