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();
}
}
答案 0 :(得分:0)
我认为你不需要在MVC应用程序中使用MemoryCache。它需要一些自定义实现才能使其正常工作。为什么不使用 HttpContext.Cache 呢? 它使用起来非常简单,可以根据自己的喜好进行配置 - 网上有很多教程。 (我刚刚做了一个小教程,如果你开始有困难,可以check it out)