List all active ASP.NET Sessions

后端 未结 9 1882
情话喂你
情话喂你 2020-11-28 22:39

How can I list (and iterate through) all current ASP.NET sessions?

9条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-28 23:05

    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!
                }
            }
        }
    }
    

提交回复
热议问题