如何在Asp.net core中缓存资源?

14

请给我一个例子。我想缓存一些在网站中大部分页面上频繁使用的对象。我不确定在MVC 6中推荐的做法是什么。

3个回答

15

startup.cs 文件中:

public void ConfigureServices(IServiceCollection services)
{
  // Add other stuff
  services.AddCaching();
}

然后在控制器中,在构造函数中添加一个 IMemoryCache,例如 HomeController:

private IMemoryCache cache;

public HomeController(IMemoryCache cache)
{
   this.cache = cache;
}

然后我们可以使用以下代码设置缓存:

public IActionResult Index()
{
  var list = new List<string>() { "lorem" };
  this.cache.Set("MyKey", list, new MemoryCacheEntryOptions()); // Define options
  return View();
}

(在设置了任何选项之后)

并从缓存中读取:

public IActionResult About()
{
   ViewData["Message"] = "Your application description page.";
   var list = new List<string>(); 
   if (!this.cache.TryGetValue("MyKey", out list)) // read also .Get("MyKey") would work
   {
      // go get it, and potentially cache it for next time
      list = new List<string>() { "lorem" };
      this.cache.Set("MyKey", list, new MemoryCacheEntryOptions());
   }

   // do stuff with 

   return View();
}

3
FYI,现在在startup.cs中使用services.AddMemoryCache()。虽然像任何预发布软件一样,这也可能再次更改。 - SergioL

15
使用ASP.NET Core中的推荐方法是使用IMemoryCache。你可以通过DI检索它。例如,CacheTagHelper就利用了它。
希望这足以让您开始缓存所有对象 :)

1
很遗憾,该链接现在返回404错误。 - NikolaiDante
@NikolaiDante - 这是因为他们将名称更改为AspNetCore,https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNetCore.Mvc.TagHelpers/CacheTagHelper.cs - Erik Funkenbusch
@ErikFunkenbusch 哦,显然。我已经更新了帖子 :-) - NikolaiDante
我的当前网站是MVC 4,我使用DevTrends Donut[Hole]Caching。看起来由于CacheTagHelper,DonutHoleCaching不再必要,这是真的吗? - ganders

3

我认为目前在ASP.net MVC 5中没有类似于OutputCache属性的可用属性。

大多数属性只是快捷方式,它们间接使用ASP.net的缓存提供程序。

同样的东西在ASP.net 5 vnext中也是可用的。 https://github.com/aspnet/Caching

这里提供不同的缓存机制,您可以使用内存缓存并创建自己的属性。

希望这有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接