Session 共享(StateServer模式)(原创)
Session 共享要注意两点:
1、必须在同一个域名下
2、StateServer模式是把session保存在同一台服务器上的进程:aspnet_state.exe里面,当然也可以保存在memcache和数据库里,这个下一节再讲。
web.config设置:
<machineKey decryptionKey="FD69B2EB9A11E3063518F1932E314E4AA1577BF0B824F369" validationKey="5F32295C31223A362286DD5777916FCD0FD2A8EF882783FD3E29AB1FCDFE931F8FA45A8E468B7A40269E50A748778CBB8DB2262D44A86BBCEA96DCA46CBC05C3" validation="SHA1" decryption="Auto"/> <sessionState cookieless="false" timeout="50" mode="StateServer" stateConnectionString="tcpip=127.0.0.1:42424"/> <httpModules> <add name="CrossDomainCookieModule" type="Entity.SessionProviderHttpModule, Entity"/> </httpModules>
tcpid的42424是默认端口
统一sessionid
要想共享session,就得把sessionid统一,sessionid是保存在cookie里ASP.NET_SessionId
public class SessionProviderHttpModule : IHttpModule { private string m_RootDomain = string.Empty; public void Dispose() { } public void Init(HttpApplication context) { Sites sites = new Sites(); m_RootDomain = sites.RootDomain; //Type stateServerSessionProvider = typeof(HttpSessionState).Assembly.GetType("System.Web.SessionState.OutOfProcSessionStateStore"); //FieldInfo uriField = stateServerSessionProvider.GetField("s_uribase", BindingFlags.Static | BindingFlags.NonPublic); //if (uriField == null) // throw new ArgumentException("UriField was not found"); //uriField.SetValue(null, m_RootDomain); context.EndRequest += new System.EventHandler(context_EndRequest); } void context_EndRequest(object sender, System.EventArgs e) { HttpApplication app = sender as HttpApplication; for (int i = 0; i < app.Context.Response.Cookies.Count; i++) { if (app.Context.Response.Cookies[i].Name == "ASP.NET_SessionId") { app.Context.Response.Cookies[i].Domain = m_RootDomain; } } } } }
这样就可以实现session共享了。