关于多台机器以前session共享,sessionState mode="StateServer" 问题的困扰

.net 多台机器共享session是很老的技术,一直不多用到session。html

最近就出现了一个问题:三台前端,其中一台保存的session值死活不对,同样的环境,同样的配置文件,就是和另外两台得到的值不一样(值老是等于每次访问这台机器时,执行写session操做的值)。前端

网上也搜了很多资料,不是什么详解,就是大全,找了很久(难道真的RP问题),终于发现解决方案,总结一下,给有须要的同窗。web

 

作好如下配置:服务器

在web.config下,<system.web>节点下插入配置cookie

<sessionState cookieName="DotNetAuth" mode="StateServer" stateConnectionString="tcpip=你的服务器IP(通常是内网):42424" cookieless="false" timeout="30" />

启动 Asp.Net Session Service 服务,在注册表 [HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\aspnet_state\Parameters] 配置端口(Port,默认是42424),和容许远程链接(AllowRemoteConnection,默认是0,0-不容许,1-容许)session

注:作好以上配置,不必定就能够成功共享session。由于你在IIS上建立的网站标识可能会不一样,标识不一样机器之间session是不能共享的(固然你运气好到爆,我也没话说)。app

解决方案一:有条件的同窗,能够保持三台服务器IIS上的站点标识ID都是同样(网站建立好,再修改不行,必定要建立时就是相同的标识ID),这样能够确定三台机器的session之间是能够共享的less

解决方案二:将园里的一段代粘贴到global.asax中,也能够解决(来至:http://www.cnblogs.com/cardgames/articles/3399546.htmltcp

public override void Init()
        {
            base.Init();
            foreach (string moduleName in this.Modules)
            {
                string 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);
                        }
                    }
                }
            }
        }

 

另附上一些参考资料:ide

sessionState详解:http://www.cnblogs.com/tangge/archive/2013/09/10/3312380.html

MSDN官方文档:https://msdn.microsoft.com/zh-cn/library/h6bb9cz9(VS.80).aspx

说说Asp.net的StateServer和Session共享:http://blog.csdn.net/ahywg/article/details/39232809

相关文章
相关标签/搜索