利用StateServer實現Session共享

1、更改web.config 中的 <sessionState mode="StateServer" stateConnectionString="tcpip=localhost:42424" cookieless="false"/>

 注:tcpip=localhost:42424  tcpip的值可以設置爲遠程電腦的ip,如果設置爲localhost說明session的值存放在本地服務器上面,如果設置爲遠程ip的話,則session存放在該遠程服務器上。

2、打開session所在服務器的“服務”設置,將“aspnet_state”服務開啓,將其設置爲自動啓動模式


3、如果session所在的服務器不是本地服務器,需要在session所在服務器的註冊器中將允許遠程訪問設置打開,HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\aspnet_state \Parameters 節點 → 將 AllowRemoteConnection 的鍵值設置成“1”(1 爲允許遠程電腦的連接,0 代表禁止)→ 設置 Port (端口號)

4、在Global.asax代碼中修改Session_Start()方法,如下:

protected void Session_Start()
        {
            foreach (string moduleName in this.Modules)
            {
                string appName = "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);
                        }
                    }
                }
            }


            if (Response.Cookies != null)
            {
                for (int i = 0; i < Response.Cookies.Count; i++)
                {
                    if (Response.Cookies[i].Name == "ASP.NET_SessionId")
                    {
                        Response.Cookies[i].Domain = ".test.com";      //一定要保持不同應用程序的"ASP.NET_SessionId"的cookie的Domain值一致
                    }
                }
            }
        }

注意:上面的代碼一定要寫在Global.asax中的Session_Start()方法中才會起作用,我看到的別人的博客中的代碼是寫在Init()方法中,但是我測試發現沒辦法實現session共享,此處給出我借鑑的博客的地址http://www.cnblogs.com/cnxkey/articles/5157498.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章