【问题标题】:How to cache resources in Asp.net core? [closed]如何在 Asp.net core 中缓存资源? [关闭]
【发布时间】:2015-02-01 23:12:50
【问题描述】:

你能给我举个例子吗?我想缓存一些会在网站上大部分页面中经常使用的对象?我不确定在 MVC 6 中推荐的做法是什么。

【问题讨论】:

    标签: asp.net-core asp.net-core-mvc


    【解决方案1】:

    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();
    }
    

    (设置任何options

    并从缓存中读取:

    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();
    }
    

    【讨论】:

    • fyi,现在是 startup.cs 中的 services.AddMemoryCache()。尽管与任何预发布软件一样,这可能会再次发生变化。
    【解决方案2】:

    在 ASP.NET Core 中推荐的方法是使用IMemoryCache。您可以通过 DI 检索它。例如,CacheTagHelper 使用它。

    希望这会给你足够的信息来开始缓存你的所有对象:)

    【讨论】:

    • 不幸的是这个链接现在是 404s
    • @NikolaiDante - 那是因为他们改名为 AspNetCore,github.com/aspnet/Mvc/blob/dev/src/…
    • @ErikFunkenbusch 啊,很明显。我已经更新了帖子:-)
    • 我当前的网站是 MVC 4,我使用 DevTrends Donut[Hole]Caching。由于 CacheTagHelper,DonutHoleCaching 似乎不再是必需的,是这样吗?
    【解决方案3】:

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

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

    在 ASP.net 5 vnext 中也有同样的功能。 https://github.com/aspnet/Caching

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

    希望对您有所帮助。

    【讨论】:

      最近更新 更多