Friday 1 February 2013

Manipulating Asp.NET Session Variables (from the server)

Based on this code sample List all active ASP.NET Sessions from StackOverflow, I wrote the following script, which uses reflection to access and modify Session values, from current ASP.NET users:
var caches = (object[])typeof(HttpRuntime).prop("CacheInternal").field("_caches");

foreach(var cache in caches)
{
    "cache: {0}".info(cache);
    var entries = (Hashtable)cache.field("_entries");
    
    foreach (DictionaryEntry entry in entries)
    {
        var key = entry.Value.prop("Key");
        var value = entry.Value.prop("Value");
        if (value.str() == "System.Web.SessionState.InProcSessionState")
        {
            "*** InProcSessionState: {0} : {1}".debug(value, key); 
            var sessionItems = (SessionStateItemCollection)value.field("_sessionItems");            
            if (sessionItems.notNull())
                foreach(string sessionItemKey in sessionItems.toList())
                {
                    "[{0}] {1} = {2}".debug(key,sessionItemKey,sessionItems[sessionItemKey]);
                    if (sessionItemKey != "sessionID")
                        sessionItems[sessionItemKey] = "<h1>from the server </h1>";
                }
        }
        
//        "    entry: {0} = {1}".info(key, value);        
    }        
}
return httpContext;

//using System.Web.SessionState;
//using System.Collections;
//using System.Web;
//O2Ref:System.Web.dll

This code was created using the C# REPL started from a Web REPL:

image

How it works?

First we set a Session Value (in a separate browser window):

image

Then running the script, note how (from a different thread in the Cassini server) we have access to the a_Key session value (top line in the Log Viewer)

image

What is more interesting, is that we can change the 'Session value' from this script:

image

Which means that If we go back to the Web REPL (and comment the Session[“a_Key”] setter), we will see it's changed value:

image