Link to home
Create AccountLog in
Avatar of Bobby X
Bobby XFlag for United States of America

asked on

Updating a Cache Object in C#

I have a cache object in C# that still has not expired yet, and I want to update the value of its key. How do I do that? This is for an ASP.NET MVC web app.  For example:

UserLogin userLogin = new UserLogin() {
  LoginAttempts = 1,
  DateTimeAttempted = DateTime.Now

if (System.Web.HttpContext.Current.Cache["LoginInfo"] == null)
   System.Web.HttpContext.Current.Cache.Insert("LoginInfo", userLogin, null, DateTime.Now.AddSeconds(60), TimeSpan.Zero);

if (System.Web.HttpContext.Current.Cache["LoginInfo"] != null && UserAuthenticationFailedAgain)
   userLogin.LoginAttempts = 2;
   userLogin.DateTimeAttempted = DateTime.Now;
   // Now how do I update the value of this existing cache object's key "LoginInfo" so that the when I access Cache["LoginInfo"].LoginAttempts and Cache["LoginInfo"]. DateTimeAttempted, I get 2 and an updated date time, respectively??  I don't see System.Web.HttpContext.Current.Cache.Update() in

Many thanks in advance.
Avatar of David Johnson, CD
David Johnson, CD
Flag of Canada image

don't worry about it.. if you change the item then the cache will realize that the item and the cached item are not identical so it will reload the item. 
Avatar of Bobby X


Ok I will try it again and see if it works
Avatar of ste5an
Flag of Germany image

Link to home
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
There's potentially a larger problem with the code though, you may want to look at reworking it a bit.
The HttpContext.Current.Cache is NOT specific to users, it's global for the app domain.

So EVERY single user that attempts to login, is going to share and update the same instance of "LoginInfo" as you have it now.

If User A fails 5 times, and then User B attempts to log in, you'll be getting the same item User A updated.