我正在使用针对 .Net 框架 4.5.2 的 Asp.net 5 和 MVC 6 我想使用以下代码:
Cache["test"] = "test";
或
HttpContext.Cache["test"] = "test";
但是两者都得到以下错误,即缓存在此上下文中不存在。 我错过了什么??
编辑:
如下所述,您可以通过将 IMemoryCache 接口(interface)注入(inject) Controller 来进行缓存。这似乎是 asp.net 5 RC1 中的新功能。
最佳答案
更新您的 startup.cs
以将其包含在 ConfigureServices
中:
services.AddCaching();
然后更新 Controller 以依赖IMemoryCache
:
public class HomeController : Controller
{
private IMemoryCache cache;
public HomeController(IMemoryCache cache)
{
this.cache = cache;
}
然后您可以在您的操作中使用它,例如:
public IActionResult Index()
{
// Set Cache
var myList = new List<string>();
myList.Add("lorem");
this.cache.Set("MyKey", myList, new MemoryCacheEntryOptions());
return View();
}
和
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
// Read cache
var myList= this.cache.Get("MyKey");
// Use value
return View();
}
很多more detail在 dotnet.today 上的 MemoryCache
上。
关于c# - 缓存 Asp.Net 不存在 Asp.Net 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34857145/