Tom el Safadi
Tom el Safadi

Reputation: 6746

Cache Asp.Net doesn't exist Asp.Net 5

I am using Asp.net 5 and MVC 6 targeting the .Net framework 4.5.2 I want to use the following code:

Cache["test"] = "test";

or

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

But both get the following error that Cache doesn't exist in this context. What am I missing??

Edit:

As answered below, you can cache using the IMemoryCache interface by injecting it into your controller. This seems to be new in asp.net 5 RC1.

Upvotes: 4

Views: 1258

Answers (2)

NightOwl888
NightOwl888

Reputation: 56849

In MVC 6, you can cache using the IMemoryCache interface by injecting it into your controller.

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

Upvotes: 2

NikolaiDante
NikolaiDante

Reputation: 18639

Update your startup.cs to have this inside ConfigureServices:

services.AddCaching();

Then update the controller to have a dependency of IMemoryCache:

public class HomeController : Controller
{
    private IMemoryCache cache;

    public HomeController(IMemoryCache cache)
    {
        this.cache = cache;
    }

Then you can use it in your actions like:

    public IActionResult Index()
    {
        // Set Cache
        var myList = new List<string>();
        myList.Add("lorem");
        this.cache.Set("MyKey", myList, new MemoryCacheEntryOptions());
        return View();
    }

And

    public IActionResult About()
    {
        ViewData["Message"] = "Your application description page.";

        // Read cache
        var myList= this.cache.Get("MyKey");

        // Use value

        return View();
    }

Much more detail on MemoryCache on dotnet.today.

Upvotes: 4

Related Questions