缓存 Asp.Net Asp.Net 5 不存在

本文关键字:Asp Net 不存在 缓存 | 更新日期: 2023-09-27 18:30:46

我正在使用针对.Net框架4.5.2的 Asp.net 5和MVC 6我想使用以下代码:

Cache["test"] = "test";

HttpContext.Cache["test"] = "test";

但两者都会收到以下错误,即缓存在此上下文中不存在。我错过了什么??

编辑:

如下所述,您可以使用 IMemoryCache 接口将其注入控制器进行缓存。这似乎是 asp.net 5 RC1 中的新功能。

缓存 Asp.Net Asp.Net 5 不存在

更新您的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();
    }

关于 dotnet.today MemoryCache的更多详细信息。

在 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();
    }
}