同一域名的ASP.NET网站实现Session共享

Session共享主要保证两点:

  1. 前台Asp_SessionId的Cookie作用域为顶级域名,且值相同
  2. 后端Session公用同一源 通过自定义HttpModule可以实现这两个需求
    /// 
    /// 自定义HttpModule,使调用本HttpModule的系统使用同一个SessionID(只限于同一个根域名),实现Session共享 /// 需要在AppSetting里面配置Domain(根域名),在system.webServer下添加自定义modules add name = "MakeSessionIDOneOnly" type="Tools.MakeSessionIDOneOnly, Tools" ///  public class MakeSessionIDOneOnly : IHttpModule { private string m_RootDomain = string.Empty; #region IHttpModule Members public void Dispose() { } ///  /// Init函数主要让本系统对应的StateServer中的Session的s_uribase(可以理解为作用域)一致,统一设置为根域名,这样相当于多套系统统一使用一个Session///  ///  public void Init(HttpApplication context) { //1.获取根域名 m_RootDomain = ConfigurationManager.AppSettings["Domain"]; //2.获取System.Web.SessionState.OutOfProcSessionStateStore类 Type stateServerSessionProvider = typeof(HttpSessionState).Assembly.GetType("System.Web.SessionState.OutOfProcSessionStateStore"); //3.获取该类的静态字段s_uribase FieldInfo uriField = stateServerSessionProvider.GetField("s_uribase", BindingFlags.Static | BindingFlags.NonPublic); if (uriField == null) throw new ArgumentException("UriField was not found"); //object obj= uriField.GetValue(null); //4.设置s_uribase值为根域名 uriField.SetValue(null, m_RootDomain); context.EndRequest += new System.EventHandler(context_EndRequest); } ///  /// 上下文结束时让输出的cookie作用域一致,统一设置为根域名 ///  ///  ///  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; } } } #endregion } 

Init方法可以实现所有使用本HttpModule的项目使用同一个源的Session,这样在输出ASP.NET_SessionId的cookie时就会是相同的值,但是Cookie作用域没办法修改。 在context_EndRquest方法中重新设定ASP.NET_SessionId的作用域为根域名即可。 在需要调用本Module的项目Web.Config中需要加入

  <system.web>
    <compilation debug="true" targetFramework="4.6.1"/> <httpRuntime targetFramework="4.6.1"/>  <sessionState mode="StateServer" stateConnectionString="tcpip=127.0.0.1:42424" timeout="30">sessionState>  <machineKey decryptionKey="FD69B2EB9A11E3063518F1932E314E4AA1577BF0B824F369" validationKey="5F32295C31223A362286DD5777916FCD0FD2A8EF882783FD3E29AB1FCDFE931F8FA45A8E468B7A40269E50A748778CBB8DB2262D44A86BBCEA96DCA46CBC05C3" validation="SHA1" decryption="Auto"/>  <httpModules> <add name="MakeSessionIDOneOnly" type="Tools.MakeSessionIDOneOnly,Tools"/> httpModules> system.web> <system.webServer> <modules>  <add name="MakeSessionIDOneOnly" type="Tools.MakeSessionIDOneOnly,Tools"/> modules> system.webServer> <appSettings>  <add key="DOMAIN" value="localhost"/> appSettings>

你可能感兴趣的:(同一域名的ASP.NET网站实现Session共享)