1、更改web.config 中的 <sessionState mode="StateServer" stateConnectionString="tcpip=localhost:42424" cookieless="false"/>
注:tcpip=localhost:42424 tcpip的值可以设置为远程电脑的ip,如果设置为localhost说明session的值存放在本地服务器上面,如果设置为远程ip的话,则session存放在该远程服务器上。
2、打开session所在服务器的“服务”设置,将“aspnet_state”服务开启,将其设置为自动启动模式
3、如果session所在的服务器不是本地服务器,需要在session所在服务器的注册器中将允许远程访问设置打开,HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\aspnet_state \Parameters 节点 → 将 AllowRemoteConnection 的键值设置成“1”(1 为允许远程电脑的连接,0 代表禁止)→ 设置 Port (端口号)
4、在Global.asax代码中修改Session_Start()方法,如下:
protected void Session_Start()
{
foreach (string moduleName in this.Modules)
{
string appName = "appName"; //一定要保持不同应用程序中的appName的值一致
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);
}
}
}
}
if (Response.Cookies != null)
{
for (int i = 0; i < Response.Cookies.Count; i++)
{
if (Response.Cookies[i].Name == "ASP.NET_SessionId")
{
Response.Cookies[i].Domain = ".test.com"; //一定要保持不同应用程序的"ASP.NET_SessionId"的cookie的Domain值一致
}
}
}
}
注意:上面的代码一定要写在Global.asax中的Session_Start()方法中才会起作用,我看到的别人的博客中的代码是写在Init()方法中,但是我测试发现没办法实现session共享,此处给出我借鉴的博客的地址http://www.cnblogs.com/cnxkey/articles/5157498.html