asp.net session共享(通过StateServer方式)

asp.net Session共享的问题在开发或部署的时候可能会遇到,怎么在不同的应用程序间共享Session呢?今天找了下,网上有不少方法,其中使用SqlServer数据库共享Session最为常见,如果需要自行百度下就出来了。但如果数据库不是SqlServer而是其他(如Oracle)岂不是麻烦大了?还好今天找了另一种方式,不使用数据库实现Session共享,即使用StateServer方式。废话少说吧,看看实现步骤:

1.打开注册表,运行cmd/regedit,找到节点HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\aspnet_state\Parameters

  a.将AllowRemoteConnection值设置为1

  [b.将Port值设置为a5b8(十六进制),即十进制42424(默认值)]

  以上根据字面意思就可以看出允许远程连接和设置端口

2.将计算机服务"ASP.NET State Service"启动类型改为自动,同时启动改服务。

3.分别在网站项目A和网站项目B的web.config文件中system.web节点下添加

  

<sessionState mode="StateServer" stateConnectionString="tcpip=192.168.0.110:42424" timeout="60"></sessionState>
cookieless="false"表示:如果用户浏览器支持Cookie时启用会话状态(默认为False)
cookieless="true"表示:如果用户浏览器不支持Cookie时启用会话状态(默认为False)

 记得替换成服务的IP和步骤1中设置的端口

4.分别在网站项目A和网站项目B的Global.asax.cs中加入下面代码

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);
                        }
                    }
                }
            }
        }

注意两个APPNAME应该设置为一样。以上就解决了Session同享的问题。以上解决方案参考了这里

最后可以测试下在网站项目A写Session在网站项目B中读取,或者在网站项目B中写Seesion在网站项目A中读取。欢迎留言

posted on 2016-01-25 15:06  &大飞  阅读(1492)  评论(0编辑  收藏  举报

导航