ASP.NET多站点Session共享
首先,这些站点的Session必须存在sqlserver中。
站点A和站点B的 web.config加入下面代码。
<machineKey validationKey="C50B3C89CB21F4F1422FF158A5B42D0E8DB8CB5CDA1742572A487D9401E3400267682B202B746511891C1BAF47F8D25C07F6C39A104696DB51F17C529AD3CABE"
decryptionKey="8A9BE8FD67AF6979E7D20198CFEA50DD3D3799C77AF2B72F" validation="SHA1" />
分别在站点A和站点B中添加一个httpmodule。
public class SharedSessionModule : IHttpModule { #region IHttpModule Members /// <summary> /// Initializes a module and prepares it to handle requests. /// </summary> /// <param name="context">An <see cref="T:System.Web.HttpApplication"/> /// that provides access to the methods, /// properties, and events common to all application objects within an ASP.NET /// application</param> public void Init(HttpApplication context) { // Get the app name from config file... string appName = ConfigurationManager.AppSettings["ApplicationName"]; if (!string.IsNullOrEmpty(appName)) { 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); } } /// <summary> /// Disposes of the resources (other than memory) used by the module that /// implements <see cref="T:System.Web.IHttpModule"/>. /// </summary> public void Dispose() { } #endregion }
两个站点的web.config加入下面代码。
<httpModules>
<add name="SharedSessionModule" type="AppNameSpace.SharedSessionModule, AppNameSpace, Version=1.0.0.0, Culture=neutral" />
</httpModules>
如果两个站点的domain name不同,还需要下面一段代码
var session = HttpContext.Current.Session; var request = HttpContext.Current.Request; var cookie = request.Cookies["ASP.NET_SessionId"]; if (cookie != null && session != null && session.SessionID != null) { cookie.Value = session.SessionID; cookie.Domain = "yourappdomain.com"; // the full stop prefix denotes all sub domains cookie.Path = "/"; // default session cookie path root }