首页 > 解决方案 > 如何在不同的网站(不同的服务器)之间共享会话

问题描述

作为要求的一部分,我需要在不同域中的 2 个不同应用程序(托管在不同机器上)之间共享一个会话。(例如: app1.domain.com 和 app2.domain.com)

我正在使用 Sql Server 会话管理,两个应用程序都指向同一个服务器来存储会话。在这两个 Web 应用程序中,机器密钥的定义相同,并且两个 Web 服务器都指向同一服务器,我在其中运行 State Server 服务以进行会话管理。

但是当我从一个应用程序重定向到另一个应用程序时,我无法读取在第一个应用程序中启动的第二个应用程序中的会话值。需要你的建议。谢谢!

下面是我对这两个应用程序的 web.config 所做的更改:

<sessionState mode="SQLServer" 
    cookieless="false" 
    timeout="20" 
    sqlConnectionString="data source= DESKTOP-565; initial catalog=ASPState; user id=sa; password=*********;" 
    allowCustomSqlDatabase="true" />

同样在Global.asax的Init()方法中,我将应用程序域名转换为一个名称,以便可以在 2 个应用程序之间共享会话。(这个方法写在两个应用程序上

public override void Init()
    {
        base.Init();
        try
        {
            // Get the app name from config file...
            string appName = "/lm/w3svc/5/root";
            if (!string.IsNullOrEmpty(appName))
            {
                foreach (string moduleName in this.Modules)
                {
                    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);
                            }
                        }
                    }
                }
            }
        }

标签: c#asp.netsessionsession-management

解决方案


推荐阅读