如何在 Asp.net core 中缓存资源? [英] How to cache resources in Asp.net core?

查看:16
本文介绍了如何在 Asp.net 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 中缓存资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆