本文介绍了如何在Asp Core中缓存资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
能给我指出一个例子吗?我想缓存一些将在网站上大多数页面上频繁使用的对象吗?我不确定在MVC 6中推荐的方法是什么.
Can you please point me to an example. I want to cache some objects that will be frequently used in most of the pages on the website? I am not sure what will be the recommended way of doing it in MVC 6.
推荐答案在startup.cs中:
public void ConfigureServices(IServiceCollection services) { // Add other stuff services.AddCaching(); }然后在控制器中,将IMemoryCache添加到构造函数中,例如对于HomeController:
Then in the controller, add an IMemoryCache onto the constructor, e.g. for HomeController:
private IMemoryCache cache; public HomeController(IMemoryCache cache) { this.cache = cache; }然后我们可以使用以下方法设置缓存:
Then we can set the cache with:
public IActionResult Index() { var list = new List<string>() { "lorem" }; this.cache.Set("MyKey", list, new MemoryCacheEntryOptions()); // Define options return View(); }(带有任何选项已设置)
(With any options being set)
并从缓存中读取:
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(); }更多推荐
如何在Asp.net Core中缓存资源?
发布评论