【发布时间】:2015-02-01 23:12:50
【问题描述】:
你能给我举个例子吗?我想缓存一些会在网站上大部分页面中经常使用的对象?我不确定在 MVC 6 中推荐的做法是什么。
【问题讨论】:
标签: asp.net-core asp.net-core-mvc
你能给我举个例子吗?我想缓存一些会在网站上大部分页面中经常使用的对象?我不确定在 MVC 6 中推荐的做法是什么。
【问题讨论】:
标签: asp.net-core asp.net-core-mvc
在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();
}
【讨论】:
在 ASP.NET Core 中推荐的方法是使用IMemoryCache。您可以通过 DI 检索它。例如,CacheTagHelper 使用它。
希望这会给你足够的信息来开始缓存你的所有对象:)
【讨论】:
我认为目前在 ASP.net MVC 5 中没有可用的类似 OutputCache 属性。
大多数属性只是快捷方式,它将间接使用缓存提供程序 ASP.net。
在 ASP.net 5 vnext 中也有同样的功能。 https://github.com/aspnet/Caching
这里有不同的缓存机制可用,您可以使用内存缓存并创建自己的属性。
希望对您有所帮助。
【讨论】: