Link to home
Start Free TrialLog 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 docs.microsoft.com
}


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

ASKER

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

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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.