Ответ 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();
}