Skip to content

Instantly share code, notes, and snippets.

@ouroborus
Created January 28, 2018 00:34
Show Gist options
  • Save ouroborus/9bf0d257c32e0f21b7bee5d4677bb565 to your computer and use it in GitHub Desktop.
Save ouroborus/9bf0d257c32e0f21b7bee5d4677bb565 to your computer and use it in GitHub Desktop.
IIS Shared Session State Hack

The usual shared session state hack doesn't clean up after itself and so can cause problems with IIS. It also isn't initialized in the right place, so can impact other modules.

We solve this by removing SessionStateModule and adding our own module which acts as a kind of wrapper that takes care of temporarily setting AppDomainAppId and loading and initializing SessionStateModule.

SessionStateModule sets up its session ID during Init along with all the hooks it needs. Conviently, this means we don't have to deal to much with special snowflake nonsense when doing MITM.

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.SessionState;
namespace org.ouroborus {
// Hack to get session state sharing between apps. Should be using a custom session state provider but no time.
public class SharedSession : IHttpModule {
SessionStateModule ssm;
public void Init(HttpApplication context) {
if(ssm == null) {
ssm = new SessionStateModule();
string tempApplicationName = Convert.ToString(ConfigurationManager.AppSettings["ApplicationName"]);
FieldInfo runtimeInfo = typeof(HttpRuntime).GetField("_theRuntime", BindingFlags.Static | BindingFlags.NonPublic);
HttpRuntime theRuntime = (HttpRuntime)runtimeInfo.GetValue(null);
FieldInfo appNameInfo = typeof(HttpRuntime).GetField("_appDomainAppId", BindingFlags.Instance | BindingFlags.NonPublic);
object originalApplicationName = appNameInfo.GetValue(theRuntime);
appNameInfo.SetValue(theRuntime, tempApplicationName);
try {
ssm.Init(context);
}
catch {
// just need the finally
throw;
}
finally {
appNameInfo.SetValue(theRuntime, originalApplicationName);
}
}
}
public void Dispose() {
if(ssm != null) {
ssm.Dispose();
ssm = null;
}
}
}
}
<!-- ... -->
<httpModules>
<remove name="Session" />
<add name="Session" type="org.ouroborus.SharedSession" />
</httpModules>
<!-- ... -->
<appSettings>
<add key="ApplicationName" value="MySharedStateApplicationName"/>
</appSettings>
<!-- ... -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment