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

时间:2016-01-18 14:29:19

标签: c# asp.net-mvc caching asp.net-core asp.net-core-mvc

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

Cache["test"] = "test";

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

但是两者都得到以下错误:Cache在此上下文中不存在。 我错过了什么?

修改

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

2 个答案:

答案 0 :(得分:4)

更新您的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 MemoryCachemore detail多{。}}。

答案 1 :(得分:2)

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