Skip to content

@jarrettmeyer /HttpSession.cs
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
Something went wrong with that request. Please try again.