When i cache an object to the HttpContext Cache, my object disappear on the next read and I must reinsert the object a second time. After that, the object stay there without any problem.

Here's what happen:

  1. Start the debugging of the mvc project
  2. Read the age from the cache
  3. The age is null so i put 50 in the variable and then insert it in the cache
  4. The user click refresh immediately
  5. Read the age from the cache
  6. The age is still null so i put 50 in the variable and then insert it in the cache
  7. The user click refresh immediately
  8. Read the age from the cache
  9. The age is there finally!

So why the Cache have this problem to keep the object in cache on the first insert?

This behavior exist in the .Net framework 3.5, 4.0, 4.5, 4.5.2.

Here's the code:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        int? age = this.HttpContext.Cache.Get("age") as int?;
        if (age == null)
        {
            age = 50;

            this.HttpContext.Cache.Insert("age", age);
        }
        return View();
    }
}

Related posts

Recent Viewed