Avatar of Bobby X
Bobby X
Flag 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.
ASP.NET.NET MVCC#

Avatar of undefined
Last Comment
Snarf0001

8/22/2022 - Mon
David Johnson, CD

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. 
Bobby X

ASKER
Ok I will try it again and see if it works
ASKER CERTIFIED SOLUTION
ste5an

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
Snarf0001

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.
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23