session的四种模式,默认的是Inproc
在负载均衡的时候使用这种模式会造成session不共享的问题,所以需要修改为StateServer模式
webconfig中SessionState需要修改为如下代码,其中stateConnectionString配置的连接是存储session的连接 可以是本机127.0.0.1。或者是其他的远程服务器,默认端口号是42424
<system.web>
<sessionState cookieless="false" timeout="120" mode="StateServer" stateConnectionString="tcpip=10.18.193.200:42424" />
</system.web>
存储session的服务器需要做一下配置修改
1.打开注册表,运行cmd/regedit,找到节点HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\aspnet_state\Parameters
a.将AllowRemoteConnection值设置为1 允许远程连接
b.将Port值设置为a5b8(十六进制),即十进制42424(默认值)
2.将计算机服务"ASP.NET State Service"启动类型改为自动,同时启动改服务。
3.分别在网站项目A和网站项目B的Global.asax.cs中加入下面代码
public override void Init()
{
base.Init();
foreach (string moduleName in this.Modules)
{
string appName = ConfigurationManager.AppSettings["SessionKey"];
IHttpModule module = this.Modules[moduleName];
SessionStateModule ssm = module as SessionStateModule;
if (ssm != null)
{
FieldInfo storeInfo = typeof(SessionStateModule).GetField("_store", BindingFlags.Instance | BindingFlags.NonPublic);
SessionStateStoreProviderBase store = (SessionStateStoreProviderBase)storeInfo.GetValue(ssm);
if (store == null)//In IIS7 Integrated mode, module.Init() is called later
{
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);
appNameInfo.SetValue(theRuntime, appName);
}
else
{
Type storeType = store.GetType();
if (storeType.Name.Equals("OutOfProcSessionStateStore"))
{
FieldInfo uribaseInfo = storeType.GetField("s_uribase", BindingFlags.Static | BindingFlags.NonPublic);
uribaseInfo.SetValue(storeType, appName);
}
}
}
}
}
配置文件中:web.config节点appsetting下增加节点
<!--给Session共享用的SessionKey -->
<add key="SessionKey" value="HrssSession" />
总结:这样就配置完毕,解决了.NET负载均衡遇到的session不共享问题, 注意点,如果未使用sessionState需要及时删除配置文件的节点,因为默认会读取配置节点,如果sessionState服务器端口不通或者sessionState服务器关闭,将会直接导致应用无法加载或者无法访问等异常问题。