c# - 缓存 Asp.Net 不存在 Asp.Net 5

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

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

Cache["test"] = "test";

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

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

编辑:

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

最佳答案

更新您的 startup.cs 以将其包含在 ConfigureServices 中:

services.AddCaching();

然后更新 Controller 以依赖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在 dotnet.today 上的 MemoryCache 上。

关于c# - 缓存 Asp.Net 不存在 Asp.Net 5,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34857145/

相关文章:

c# - Windows 服务 - 如何使名称可配置

c# - 识别扩展方法的反射(reflection)

c# - 将 String 或 Char 转换为 Keys 对象

asp.net-mvc - 这个端口号 http ://localhost:52432/specified when running an ASP. NET MVC 应用程序在哪里?

C# ASP.NET MVC 模型绑定(bind)

asp.net - 可以在 Web 应用程序中使用 WPF 程序集吗?

c# - Lambda 表达式中的动态 Where 子句

swift - 图片不使用 Firebase url 缓存,但使用其他缓存

java - WeakReference 是我需要的吗?

在加载 200mb 的新图像()后,Javascript 在 Safari/iPad2 中运行缓慢。为什么会这样?