在asp.net中共享域之间的会话数据,很困惑!

时间:2010-06-03 15:49:50

标签: asp.net subdomain

好的,这是我的问题,我想在两个应用程序或域之间维护会话数据(例如: - www.abc.com和secure.abc.com)。

我已经在网上阅读了这篇文章,但许多人指出了许多不同的方法来做这件事,人们评论+ ve和-ve回应所有人。此外,许多人只提供理论上的答案,做到这一点,但根本没有代码。

这些步骤都是必需的吗? 1)在web.config中:<httpCookies domain=".abc.com"/>

2)将会话数据存储在sql DB中:(在准备用于存储会话的数据库之后)

<sessionState mode="SQLServer" sqlConnectionString="Data Source=YourServer;
Integrated Security=True;database=MySessionDB" sqlCommandTimeout="30" 
allowCustomSqlDatabase="true"/>
<machineKey decryption="AES" validation="SHA1" decryptionKey="..." validationKey="..." />

3)对此问题感到困惑:我想像这样设置会话cookie的域名 Response.Cookies [“ASP.NET_SessionId”]。Domain =“。abc.com”; 但是这段代码应该写在哪里? 此条目:http://mgrzyb.blogspot.com/2007/12/aspnet-and-subdomains.html说:使用System.Web.SessionState.SessionIDManager作为基类,但SaveSessionID方法不是虚拟的,因此无法覆盖。选项包括:显式重新实现接口方法或装饰SessionIDManager类,并在调用SessionIDManager.SaveSessionID后将Response.Cookies [SessionIdCookieName] .Domain设置为我们的域。

只有作者提供了真实的代码,第3步才会明确。

任何人都可以为它提供代码。

加上所有这3个步骤足以在域名之间分享会话?

1 个答案:

答案 0 :(得分:1)

第3步语句可以根据:http://www.know24.net/blog/ASPNET+Session+State+Cookies+And+Subdomains.aspx

在global.asax中编写
protected  void Application_PreRequestHandlerExecute(Object sender, EventArgs e)

{

  /// only apply session cookie persistence to requests requiring session information



  #region session cookie

  if (Context.Handler is IRequiresSessionState || Context.Handler is IReadOnlySessionState )

  {

    /// Ensure ASP.NET Session Cookies are accessible throughout the subdomains.



    if (Request.Cookies["ASP.NET_SessionId"] != null && Session != null && Session.SessionID != null)

    {

      Response.Cookies["ASP.NET_SessionId"].Value = Session.SessionID;

      Response.Cookies["ASP.NET_SessionId"].Domain = ".abc.com"; // the full stop prefix denotes all sub domains

      Response.Cookies["ASP.NET_SessionId"].Path = "/"; //default session cookie path root         

    }

  }

  #endregion    

}