ResponseCache在某种程度上是OutputCache的替代品;但是,我想做服务器端缓存以及每个参数输入。
根据here和here的一些回答,我应该使用IMemoryCache或IDistributedCache来做这件事。我特别感兴趣的是参数不同的控制器上的缓存,以前在asp.net 4中使用OutputCache和VaryByParam完成的缓存如下所示:
[OutputCache(CacheProfile = "Medium", VaryByParam = "id", Location = OutputCacheLocation.Server)]
public ActionResult Index(long id)
{
///...
}我该如何在asp.net核心中复制它呢?
发布于 2017-06-14 00:42:57
首先,确保您使用的是ASP.NET Core1.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
发布于 2019-11-22 17:12:59
如果您想通过控制器中所有请求中的所有请求查询参数来更改缓存:
[ResponseCache(Duration = 20, VaryByQueryKeys = new[] { "*" })]
public class ActiveSectionController : ControllerBase
{
//...
}发布于 2018-08-28 23:08:53
对于那些正在寻找答案的人来说...毕竟,现在有了IMemoryCache,但不像以前的ActionFilterAttribute那么漂亮,但更灵活。
长话短说(主要针对.Net核心2.1,由微软文档+我的理解):
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:
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))); 结束。
https://stackoverflow.com/questions/35028053
复制相似问题