Reputation: 2929
In cookies we can use the Expires
(http://msdn.microsoft.com/en-us/library/system.net.cookie.expires%28VS.80%29.aspx) to define the expiration date.
In .Net 4.0 (MVC) is it possible to define a session timeout different just for one variable?
I am really not a big fan of having something similar to:
session["VariableCreatedOn"] = DateTime.Now()
session["VariableValue"] = xxx
And then try to verify if the VariableCreatedOn
is older than XYZ.
By default is there a solution for this?
Upvotes: 2
Views: 1418
Reputation: 60792
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 here 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 under the link there too.
Upvotes: 3
Reputation: 4671
No, it's not possible to directly have one session variable expire while the rest of the session lives on, or vice versa.
Rather than have to check whether the value has expired all over the place, though, you could wrap this logic in a custom class and store an object of that class in the session (instead of storing the value and the expiry-date or creation-date as two separate values).
It would work similarly to nullable value types, in that you'd have a Value property on that class, and the getter for that property would either return a value or return null depending on the value of an internal CreationDate property.
Untested code follows; adapt as per your specific needs.
public class ExpiringSessionValue<T>
{
private T _value;
private DateTime _created = DateTime.Now;
public ExpiringSessionValue(T value)
{
_value = value;
}
public T Value
{
get
{
if (_created >= DateTime.Now.AddMinutes(-10))
return _value;
else
return default(T);
}
}
}
Upvotes: 2