public
Created

How to work with sessions in .NET

  • Download Gist
HttpSession.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
public abstract class HttpSession : IHttpSession
{
protected IKeyValueStore storage;
public virtual int UserId
{
get { return Get<int>("user_id"); }
set { storage["user_id"] = value; }
}
public virtual void ResetSession()
{
UserId = 0;
}
protected virtual T Get<T>(string key)
{
try
{
var obj = storage[key];
return (T)obj;
}
catch (Exception)
{
// This should really catch KeyNotFoundException, InvalidCastException, etc.,
// but I am being lazy for demo purposes.
return default(T);
}
}
}
HttpSessionKeyValueStore.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
public class HttpSessionKeyValueStore : IKeyValueStore<string, object>
{
private readonly HttpSessionStateBase session;
public HttpSessionKeyValueStore(HttpSessionStateBase session)
{
if (session == null)
throw new ArgumentNullException("session");
this.session = session;
}
public IEnumerable<string> Keys
{
get
{
foreach (var key in session.Keys)
yield return key.ToString();
}
}
public object this[string key]
{
get { return session[key]; }
set { session[key] = value; }
}
}
IKeyValueStore.cs
C#
1 2 3 4 5
public interface IKeyValueStore<TKey, TValue>
{
IEnumerable<TKey> Keys { get; }
TValue this[TKey key] { get; set; }
}
InMemoryHttpSession
1 2 3 4 5 6 7
public class InMemoryHttpSession : HttpSession
{
public InMemoryHttpSession()
{
this.storage = new InMemoryKeyValueStore();
}
}
InMemoryKeyValueStore.cs
C#
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
public class InMemoryKeyValueStore : IKeyValueStore<string, object>
{
private readonly Dictionary<string, object> dictionary = new Dictionary<string, object>();
public IEnumerable<string> Keys
{
get { return dictionary.Keys; }
}
public object this[string key]
{
get { return dictionary[key]; }
set { dictionary[key] = value; }
}
}
WebHttpSession
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
public class WebHttpSession : HttpSession
{
private readonly HttpSessionStateBase session;
 
public WebHttpSession(HttpSessionStateBase session)
{
if (session == null)
throw new ArgumentNullException("session");
 
this.session = session;
this.storage = new HttpSessionKeyValueStore(session);
}
 
public override void ResetSession()
{
session.Clear();
base.ResetSession();
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.