.net 多台機器共享session是很老的技術,一直很少用到session。
最近就出現了一個問題:三台前端,其中一台保存的session值死活不對,一樣的環境,一樣的配置文件,就是和另外兩台獲得的值不同(值總是等於每次訪問這台機器時,執行寫session操作的值)。
網上也搜了不少資料,不是什么詳解,就是大全,找了好久(難道真的RP問題),終於發現解決方案,總結一下,給有需要的同學。
做好以下配置:
在web.config下,<system.web>節點下插入配置
<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。因為你在IIS上創建的網站標識可能會不同,標識不同機器之間session是不能共享的(當然你運氣好到爆,我也沒話說)。
解決方案一:有條件的同學,可以保持三台服務器IIS上的站點標識ID都是一樣(網站創建好,再修改不行,一定要創建時就是相同的標識ID),這樣可以肯定三台機器的session之間是可以共享的
解決方案二:將園里的一段代粘貼到global.asax中,也可以解決(來至:http://www.cnblogs.com/cardgames/articles/3399546.html)
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); } } } } }
另附上一些參考資料:
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