ead*_*dam 11 asp.net-core-mvc asp.net-core
你能指点我一个例子.我想缓存一些在网站上的大多数页面中经常使用的对象?我不确定在MVC 6中推荐的方法是什么.
N. *_*len 15
在ASP.NET Core中推荐的方法是使用IMemoryCache.您可以通过DI检索它.例如,CacheTagHelper利用它.
希望这应该给你足够的信息来开始缓存你的所有对象:)
Nik*_*nte 13
在startup.cs:
public void ConfigureServices(IServiceCollection services)
{
// Add other stuff
services.AddCaching();
}
Run Code Online (Sandbox Code Playgroud)
然后在控制器中,IMemoryCache在构造函数上添加一个,例如HomeController:
private IMemoryCache cache;
public HomeController(IMemoryCache cache)
{
this.cache = cache;
}
Run Code Online (Sandbox Code Playgroud)
然后我们可以设置缓存:
public IActionResult Index()
{
var list = new List<string>() { "lorem" };
this.cache.Set("MyKey", list, new MemoryCacheEntryOptions()); // Define options
return View();
}
Run Code Online (Sandbox Code Playgroud)
(正在设置任何选项)
并从缓存中读取:
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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7744 次 |
| 最近记录: |