How set a Session variable expired time on MVC 5?

11,446

Solution 1

Sorry guys, I finally use this solution:

when generate the Verification Code I will save it to session

Session["VerificationCode"] = code;

That's everybody knows. but how about the time? I change it :

Session["VerificationCode"] = code;
Session["VerificationTime"] = DateTime.Now; 

Now the time save in session too. Then I can find it when User Login:

 // Verification Code Expired
 if ((DateTime)Session["VerificationTime"]).AddMinutes(1) < DateTime.Now)
 {
       ModelState.AddModelError("VerificationCode", "Verification Code Expired!");
       return View(adminLogin);
 }
 // Verification Code Error
 if (Session["VerificationCode"].ToString().ToUpper() != adminLogin.VerificationCode.ToUpper())
 {
       ModelState.AddModelError("VerificationCode", "Verification Code Error");
       return View(adminLogin);
 }

Solution 2

There's no built-in way, BUT you can achieve it very simple:

Session[name] = value;

//now add a cleanup task that will run after the specified interval
Task.Delay(expireAfter).ContinueWith((task) => {
    Session.Remove(name);
});

I wrapped this into a very handy "session extender" class source code here you can use it like this:

//store and expire after 5 minutes
Session.AddWithTimeout("key", "value", TimeSpan.FromMinutes(5));

PS. If you're still using an old .NET version (no async code, no tasks) you'll find a compatible version in my blogpost as well.

Solution 3

You should create a class or structure that is stored in SessionState rather than just storing the verification code itself. This will allow you to easily check the code and the expiration date of the code.

E.g.:

public class VerificationCode {
    public string Code { get; set; }
    public DateTime ExpirationDate { get; set; }
}

// in your method
VerificationCode newCode = new VerificationCode {
                                         Code="1559",
                                         ExpirationDate = System.DateTime.Now.AddMinutes(1)
                                     };
Session["VerificationCode"] = newCode;


// in the method where you check the expiration date and code...
VerificationCode code = (VerificationCode)Session["VerificationCode"];

// you can remove the verification code after pulling it out, as you only need
//  it once, regardless of whether it is still good or expired.
Session.Remove("VerificationCode");

if (code.ExpirationDate < System.DateTime.Now){
   // the verification code expired...

   // can remove the verification code after successful login
   Session.Remove("VerificationCode");
} else {
  // verification code is still good.
  // Log the user in?

  // can remove the verification code after successful login
  Session.Remove("VerificationCode");
}

Updated - Added removal of verification code from session when expired OR upon successful login. - square bracket accessor for Session variables. Previously used VB (doh!) syntax (parentheses)

Solution 4

You can't change session time for one particular case. Instead you can use Cache.Add method with absoluteExpiration parameter to store VerificationCode in the Cache.

MemoryCache.Default.Add([UserIdentity], [Verification Code], 
    new DateTimeOffset().ToOffset(TimeSpan.FromMinutes(1)));

And then get it from Cache

var verificationCode = MemoryCache.Default.Remove([UserIdentity]);
Share:
11,446
qakmak
Author by

qakmak

Updated on July 25, 2022

Comments

  • qakmak
    qakmak almost 2 years

    I need to Generate a Verification Code like: 1599 for Login.

    The User must input correct number when Login in.

    But My default session expired time is 30 minute.

    I don't want let the Verification Code expired time so long. I just need it keep only 1 minute. So How I set expired time out only for the Verification Code session variable?

    Update1:

    I don't want to change the global session expired time. I just need set only for the Verification Code session variable before login.