How can I list (and iterate through) all current ASP.NET sessions?
I've been looking around for an equivalent of @ajitdh's answer for later versions of ASP.net - couldn't find anything, so thought I'd update this thread with solution for v4.6.2... Haven't tested with later versions of .net, but it doesn't work with v4.5. I am guessing it will be compatible with v4.6.1 onward.
Cache cache = HttpRuntime.Cache;
MethodInfo method = typeof( System.Web.Caching.Cache ).GetMethod( "GetInternalCache", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy );
object objx = method.Invoke( cache, new object[] { false } );
FieldInfo field = objx.GetType().GetField( "_cacheInternal", BindingFlags.NonPublic | BindingFlags.FlattenHierarchy | BindingFlags.Instance );
objx = field.GetValue( objx );
field = objx.GetType().GetField( "_cachesRefs", BindingFlags.NonPublic | BindingFlags.FlattenHierarchy | BindingFlags.Instance );
objx = field.GetValue( objx );
IList cacherefs = ( (IList)objx );
foreach( object cacheref in cacherefs )
{
PropertyInfo prop = cacheref.GetType().GetProperty( "Target", BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance );
object y = prop.GetValue( cacheref );
field = y.GetType().GetField( "_entries", BindingFlags.NonPublic | BindingFlags.FlattenHierarchy | BindingFlags.Instance );
Hashtable c2 = (Hashtable)field.GetValue( y );
foreach( DictionaryEntry entry in c2 )
{
object o1 = entry.Value.GetType().GetProperty( "Value", BindingFlags.NonPublic | BindingFlags.Instance ).GetValue( entry.Value, null );
if( o1.GetType().ToString() == "System.Web.SessionState.InProcSessionState" )
{
SessionStateItemCollection sess = (SessionStateItemCollection)o1.GetType().GetField( "_sessionItems", BindingFlags.NonPublic | BindingFlags.Instance ).GetValue( o1 );
if( sess != null )
{
// Do your stuff with the session!
}
}
}
}