缓存 Asp.Net 不存在 Asp.Net 5
Cache Asp.Net doesn't exist Asp.Net 5
我正在使用 Asp.net 5 和 MVC 6,目标是 .Net Framework 4.5.2
我想使用以下代码:
Cache["test"] = "test";
或
HttpContext.Cache["test"] = "test";
但两者都收到以下错误,即缓存在此上下文中不存在。
我错过了什么??
编辑:
如下所述,您可以通过将 IMemoryCache 接口注入控制器来进行缓存。这似乎是 asp.net 5 RC1 中的新功能。
更新你的 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();
}
MemoryCache
dotnet.todaymore detail。
在 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();
}
}
我正在使用 Asp.net 5 和 MVC 6,目标是 .Net Framework 4.5.2 我想使用以下代码:
Cache["test"] = "test";
或
HttpContext.Cache["test"] = "test";
但两者都收到以下错误,即缓存在此上下文中不存在。 我错过了什么??
编辑:
如下所述,您可以通过将 IMemoryCache 接口注入控制器来进行缓存。这似乎是 asp.net 5 RC1 中的新功能。
更新你的 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();
}
MemoryCache
dotnet.todaymore detail。
在 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();
}
}