Setting a different timeout for different session variables in ASP.Net.

Is it possible to set a different timeout for another session in ASP.Net?

Edited I mean that on the same page I have 2 sessions of the variable Session ["ss1"] and Session ["ss2"], can I set a timeout for each session? Or is there anyway to do the same thing as storing a session in a cookie and setting an expiration date? Sry im new to ASP.Net

+5
source share
5 answers

I wrote a very simple extension class that does this. You can find the source code here.

Using:

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

, - ...

HttpContext.Current.Session.Timeout = 540;
+3

- , Global.asax, Session_Start, - -

0

- . cookie, ( ).

- . , , , cookie, .

. , -, .

, API CodePlex:

http://www.univar.codeplex.com

2.0 , - .

0
/// <summary>
/// this class saves something to the Session object
/// but with an EXPIRATION TIMEOUT
/// (just like the ASP.NET Cache)
/// (c) Jitbit 2011. MIT license
/// usage sample:
///  Session.AddWithTimeout(
///   "key",
///   "value",
///   TimeSpan.FromMinutes(5));
/// </summary>
public static class SessionExtender
{
  public static void AddWithTimeout(
    this HttpSessionState session,
    string name,
    object value,
    TimeSpan expireAfter)
  {
    session[name] = value;
    session[name + "ExpDate"] = DateTime.Now.Add(expireAfter);
  }

  public static object GetWithTimeout(
    this HttpSessionState session,
    string name)
  {
    object value = session[name];
    if (value == null) return null;

    DateTime? expDate = session[name + "ExpDate"] as DateTime?;
    if (expDate == null) return null;

    if (expDate < DateTime.Now)
    {
      session.Remove(name);
      session.Remove(name + "ExpDate");
      return null;
    }

    return value;
  }
}
Usage:

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

//get the stored value
Session.GetWithTimeout("key");

from Alex. CEO, founder https://www.jitbit.com/alexblog/196-aspnet-session-caching-expiring-values/

0
source

All Articles