我的前面一篇文章提到了如何在使用了ASP.NET form authentication的二級網站之間共用登陸狀態,
http://www.cnblogs.com/jzywh/archive/2007/09/23/902905.html,
今天, 我要寫的是如何在次層網域網站之間,主要站台和次層網域網站之間共用Session。
首先, Session要共用,網站之間SessionID必須要一致,那怎麼保證SessionID一致呢?
ASP.NET中的SessionID是儲存在用戶端的cookie之中索引值為ASP.NET_SessionId用來維護瀏覽者Session對應關係的一個字串,要想在次層網域網站之間,主要站台和次層網域網站共用SessionID就必須先共用,那麼我們就必須先實現ASP.NET_SessionId這一cookie的共用。
CrossDomainCookieModule
------------------------------------------------------------------------------------------------
public class CrossDomainCookie : IHttpModule { private string m_RootDomain = string.Empty; #region IHttpModule Members public void Dispose() { } public void Init(HttpApplication context) { m_RootDomain = ConfigurationManager.AppSettings["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++) { app.Context.Response.Cookies[i].Domain = m_RootDomain; } } #endregion }
上面的Module重設了所有cookie的domain到root domain, root domain在web.config中設定。也許有人會說這是眉毛鬍子一把抓重寫了所有cookie的domain, 那他也可以判斷一下cookie的name, 如果為ASP.NET_SessionId的話才重寫。
如果主要站台和次層網域網站是同一網站,那麼做到這一步,你的session就已經共用了,因為Session的ID是相同的,而且Session容器也是同一個。
如果主要站台和次層網域網站是兩個不同網站,則需要進行更多的操作了。
如果兩個網站是不同的伺服器的話,解決方案要簡單點:
1) 使用相同的state server來儲存Session.
2) 在兩個網站的web.config設定相同的machineKey.
MachineKey的設定請參考http://msdn.microsoft.com/zh-cn/asp.net/w8h3skw9.aspx
3) 給兩個網站設定相同name
這樣做是為了確保兩個網站的siteID相同,siteID是site name的hash值,注意請不要使用預設網站,因為預設網站的siteID並非site name的hash.
如果兩個網站是在同一的伺服器的話,需要對CrossDomainCookie再作一下修改,此方法也可應用於兩個網站在不同伺服器的情況:
1) 使用相同的state server來儲存Session.
2) 用反射來設定System.Web.SessionState.OutOfProcSessionStateStore的靜態欄位s_uribase的值
public class CrossDomainCookie : IHttpModule { private string m_RootDomain = string.Empty; #region IHttpModule Members public void Dispose() { } public void Init(HttpApplication context) { m_RootDomain = ConfigurationManager.AppSettings["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++) { app.Context.Response.Cookies[i].Domain = m_RootDomain; } } #endregion }
完成這樣的修改之後就可以實現Session的共用了。
同樣如果你是使用SQL server來儲存Session, 也可以使用類似的方法來解決Session共用問題。
樣本檔案下載 http://files.cnblogs.com/jzywh/ShareSessionSample.zip