MemoryCache.Default invalidated after first Request

61 views Asked by At

I have the weirdest problem - just started using MemoryCache and thought it would be pretty straightforward... turns out it isn't. This is a completely empty ASP.NET MVC5 application, hosted on my local IIS 7.5

On the first request the value should have been added to the cache - so if I refresh the page, the cache should hold the value.

When I debug the application, the breakpoint (on my commented line) gets hit twice: on first request, on second request. After that the cached value can be used.

Why does the cache not return the value on the first reload as expected?

public class Temp
{
    public int Age { get; set; }
}

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var temp = (Temp)MemoryCache.Default.Get("MyVal");

        if (temp == null)
        {
            // THIS GETS HIT ON THE FIRST TWO REQUESTS, AFTER THAT THE CACHE RETURNS THE VALUE
            temp = new Temp { Age = -127 };
            MemoryCache.Default.Add("MyVal", temp, DateTime.UtcNow.AddMinutes(10));
        }


        return View();
    }
}
1

There are 1 answers

0
stann1 On

I do not think that you need to use MemoryCache in an MVC app. It requires a bit of custom implementation to get it working. Why not use the HttpContext.Cache instead? It is extremely simple to use and can be configured to your liking - there are a lot of tutorials on the web. (I made a small tutorial a while ago, you can check it out if you have trouble starting)