请给我一个例子。我想缓存一些在网站中大部分页面上频繁使用的对象。我不确定在MVC 6中推荐的做法是什么。
请给我一个例子。我想缓存一些在网站中大部分页面上频繁使用的对象。我不确定在MVC 6中推荐的做法是什么。
在 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();
}
(在设置了任何选项之后)
并从缓存中读取:
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 MVC 5中没有类似于OutputCache属性的可用属性。
大多数属性只是快捷方式,它们间接使用ASP.net的缓存提供程序。
同样的东西在ASP.net 5 vnext中也是可用的。 https://github.com/aspnet/Caching
这里提供不同的缓存机制,您可以使用内存缓存并创建自己的属性。
希望这有所帮助。