C# OutputCache/ResponseCache变量参数

C# OutputCache/ResponseCache变量参数,c#,asp.net-web-api,asp.net-caching,asp.net-core-1.0,C#,Asp.net Web Api,Asp.net Caching,Asp.net Core 1.0,ResponseCache在某种程度上替代了OutputCache;但是,我想做服务器端缓存以及按参数输入 根据一些答案和建议,我应该使用IMemoryCache或IDistributedCache来完成此操作。我特别感兴趣的是参数不同的控制器上的缓存,以前在asp.net 4中使用OutputCache和VaryByParam这样做: [OutputCache(CacheProfile = "Medium", VaryByParam = "id", Location = OutputCache

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

根据一些答案和建议,我应该使用
IMemoryCache
IDistributedCache
来完成此操作。我特别感兴趣的是参数不同的控制器上的缓存,以前在asp.net 4中使用
OutputCache
VaryByParam
这样做:

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

如何在asp.net core中复制此文件?

首先确保您使用的是asp.net core 1.1或更高版本

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

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

来源:

对于那些正在寻找答案的人。。。毕竟,现在已经没有以前那么漂亮了,但有了更多的灵活性。
长话短说(对于.Net core 2.1,主要由Microsoft docs+my understands提供):
1-添加
services.AddMemoryCache()Startup.cs
文件中将代码>服务导入
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

公共枚举缓存键{someKey,anotherKey,…}

3-在操作方法中使用它:
对于获取缓存值:
\u cache.TryGetValue(CacheKeys.SomeKey,out someValue)

如果失败,则重置值:

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

结束。

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

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

在asp.net核心中使用此选项

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

你解决了吗?