Skip to content

Instantly share code, notes, and snippets.

@jarrettmeyer
Created February 17, 2013 14:58
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jarrettmeyer/4971798 to your computer and use it in GitHub Desktop.
How to work with sessions in .NET
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);
}
}
}
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; }
}
}
public interface IKeyValueStore<TKey, TValue>
{
IEnumerable<TKey> Keys { get; }
TValue this[TKey key] { get; set; }
}
public class InMemoryHttpSession : HttpSession
{
public InMemoryHttpSession()
{
this.storage = new InMemoryKeyValueStore();
}
}
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; }
}
}
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();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment