I like to create a session value that expires in 5 minutes.
How to do that, do I need to manually compare creation time when I read it?
Session("sessionval") = myvariable
Session("sessioncreated") = now
Actually, the session variables does not expire, but the session does.
If your Internet connection is unstable, periodically disconnecting and reconnecting, it can cause a website session to expire. When the Internet connection is lost the website connection can be terminated, resulting in a session expired message if you try to access any page after the Internet reconnects.
Click Servers > Server Type > WebSphere Application Servers > CongnosX_GW2. Click Container Settings > Session management > Set Timeout. Enter the desired timeout value in minutes. Click OK.
If you are asking how to do it on a single variable I do not think it is possible, but you can define the session timeout period using the web.config
<system.web>
<sessionState timeout="5" />
<system.web>
this would affect all of your session objects, not just a single one.
My suggestion for giving a custom expiration date to a single item is to create a cookie, that way you can actually set it's expiration value.
Response.Cookies.Add(New Web.HttpCookie("AdminID", admin.AdminID))
Response.Cookies("AdminID").Expires = Now.AddMinutes(5)
you can not define custom timeout to a session variable.
Maybe you can use cache for this, with a unique key dependent to session.
You can set timeout to a cached item.
Cache.Insert("key_dependent_to_session", value, Nothing,
DateTime.Now.AddMinutes(5), TimeSpan.Zero)
If you want to use the SessionState you could create your own wrapper so instead of caching the actual item, you can cache the wrapper. Here is a quick dirty untested example of a wrapper that checks if the item is null, or if it has expired it will call a Func that you can provide a refreshed item.
The Func takes the last set value so if you can determine if the value is still valid you could avoid reloading it.
public class TimeExpirationItem<T>
{
private T _item=default(T);
private TimeSpan _expirationDuration;
private Func<T> _getItemFunc;
private DateTime _expiresTime;
public TimeExpirationItem(TimeSpan expirationDuration, Func<T, T> getItemFunc)
{
this._getItemFunc = getItemFunc;
this._expirationDuration = expirationDuration;
}
public T Item
{
get
{
if (_item == null || ItemIsExpired())
{
_item = _getItemFunc(_item);
_expiresTime = DateTime.Now.Add(_expirationDuration);
}
return _item;
}
}
public bool ItemIsExpired()
{
return DateTime.Now > _expiresTime;
}
}
Again this code is provided as is with no warranty and it is untested but is an example of the things you can do.
Using it would be something like the following:
Session.Add("ObjectKey",new TimeExpirationItem<MyObject>(new TimeSpan(0,0,5),mo=>MyObjectRepository.GetItemByLogin(Request.User.Identity.Name));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With