我使用的是针对Asp.net框架4.5.2的.Net 5和MVC 6,我想使用以下代码:
Cache["test"] = "test";或
HttpContext.Cache["test"] = "test";但是,两者都得到了以下错误,即在此上下文中不存在缓存。我遗漏了什么??
编辑:
如下所示,您可以通过将IMemoryCache接口注入控制器来使用它来缓存。这在asp.net 5 RC1中似乎是新的。
发布于 2016-01-18 17:26:43
在MVC 6中,您可以通过将IMemoryCache接口注入控制器来缓存。
using Microsoft.Extensions.Caching.Memory;
public class HomeController
{
private readonly IMemoryCache _cache;
public HomeController(IMemoryCache cache)
{
if (cache == null)
throw new ArgumentNullException("cache");
_cache = cache;
}
public IActionResult Index()
{
// Get an item from the cache
string key = "test";
object value;
if (_cache.TryGetValue(key, out value))
{
// Reload the value here from wherever
// you need to get it from
value = "test";
_cache.Set(key, value);
}
// Do something with the value
return View();
}
}发布于 2016-01-18 17:20:14
更新您的startup.cs,使其包含在ConfigureServices中
services.AddCaching();然后更新控制器,使其具有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();
}更详细 on MemoryCache on dotnet.today。
https://stackoverflow.com/questions/34857145
复制相似问题