【问题标题】:Cache Asp.Net doesn't exist Asp.Net 5缓存 Asp.Net 不存在 Asp.Net 5
【发布时间】:2016-04-23 18:24:07
【问题描述】:

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

Cache["test"] = "test";

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

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

编辑:

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

【问题讨论】:

  • 你在哪里访问缓存?
  • 我无法复制它。 public ActionResult Index() {HttpContext.Cache["Name"] = 123; var value = HttpContext.Cache["Name"]; return View();}能否创建一个新的 ASP.Net 项目再试一次?
  • 是的,我创建了一个新项目它仍然说HttpContext不包含缓存的定义,这很奇怪,我必须添加一些包或指令吗?
  • 试试HttpRuntime.Cache?

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


【解决方案1】:

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

more detail on MemoryCache on dotnet.today。

【讨论】:

    【解决方案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();
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-09-26
      • 1970-01-01
      • 2010-09-05
      • 2011-09-09
      • 2010-11-10
      • 1970-01-01
      相关资源
      最近更新 更多