【问题标题】:Session State shares session across subdomain, VB.NET website C# MVC 4 Application会话状态跨子域共享会话,VB.NET 网站 C# MVC 4 应用程序
【发布时间】:2013-10-23 10:28:30
【问题描述】:

我正在尝试从主 VB.Net 网站和子域 C# MVC 4 共享会话。

两个站点都存在相同的 ASP.NET_SessionId Cookie,在即时调试器中,我可以看到两个 Session 对象具有相同的 SessionID。但是,当我从 VB.Net 网站 Session("TestSession") = "SimpleString" 设置会话时,如果我从 MVC 应用程序调用即时窗口中的会话对象,则计数为 0。

如果我在 MVC 应用程序中设置会话,在 VB.Net 网站中找不到它,情况也是如此。

我最好使用 StateServer 模式,但我读到只有 SQLServer 模式适用于跨域支持。

这是两个站点中都存在的 web.config

<httpCookies domain=".example.localhost"/>
<sessionState mode="SQLServer" sqlConnectionString="Data Source=(local);Integrated Security=True" />
<machineKey validationKey="XXX" decryptionKey="XXX" validation="SHA1" compatibilityMode="Framework20SP1" />

【问题讨论】:

    标签: c# asp.net asp.net-mvc vb.net session


    【解决方案1】:

    为了解决问题以及添加 web.config 设置,我必须在 global.asax 中的 Application_Start 中添加几行。这必须添加到两个站点。

    C#

    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, "MyApplicationName");
    

    VB.Net

    Dim runtimeInfo As System.Reflection.FieldInfo = GetType(HttpRuntime).GetField("_theRuntime", System.Reflection.BindingFlags.[Static] Or System.Reflection.BindingFlags.NonPublic)
    Dim theRuntime As HttpRuntime = DirectCast(runtimeInfo.GetValue(Nothing), HttpRuntime)
    Dim appNameInfo As System.Reflection.FieldInfo = GetType(HttpRuntime).GetField("_appDomainAppId", System.Reflection.BindingFlags.Instance Or System.Reflection.BindingFlags.NonPublic)
    appNameInfo.SetValue(theRuntime, "MyApplicationName")
    

    【讨论】:

    • 如果应用程序位于不同的子域上,这将不起作用。
    • @MichaelFry 这已部署到不同的子域并正常工作。
    • 你是对的,它确实有效。不知道之前出了什么问题……哦,干杯!
    【解决方案2】:

    您应该使用 cookie 而不是会话变量。会话变量保存在服务器上,因此当您转到另一台服务器时,它不会有您的会话变量。

    请参阅此 SO 问题了解更多详情:where-are-the-session-variables-saved

    【讨论】:

    • 你错了,你可以使用 sessionState 创建一个会话服务器,网站连接到他们的会话......碰巧我已经解决了这个问题并且它有效
    • @AshleyMedway 如果你已经解决了这个问题,你应该把它作为一个答案,然后将它标记为已回答。这样其他有相同问题的人可以找到他们的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-21
    • 1970-01-01
    • 2011-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多