ASP.NET中解决跨子域的Session共享 demo 下载

多个站点间session共享,例如:1.1.com;2.1.com;3.1.com  等类似站点之间的session共享。找了很久的资料,今天终于解决了!点击下载demo
 
具体配置:

1.在项目中添加引用  WebLibrary.dll    (demo 已经包含 WebLibrary.dll文件)

2.在 web.config 的 appsetting 节点中添加主站域名。
 
   例如:<add key="RootDomain" value=".你的域名.com"/>  注意:域名前面的那个点不要掉。

3.在 web.config 的 system.web 节点中添加
<httpModules>
   <add name="CrossDomainCookieModule" type="WebLibrary.CrossDomainCookie, WebLibrary"/>
</httpModules>

4.在web.config的system.web节点中修改session存储方式为stateserver
   <sessionState mode="StateServer" stateConnectionString="tcpip=服务器ip地址:42424" timeout="30" />

5.在web.config的system.webServer几点中添加
<modules>
   <add name="CrossDomainCookieModule" preCondition="managedHandler" type="WebLibrary.CrossDomainCookie, WebLibrary"/>
</modules>

注意点:
1.服务器 aspnet_state 服务开启。
2. 修改服务器 注册表“HKEY_LOCAL_MACHINE/SYSTEM/ControlSett001/Services/aspnet_state/Parameters“修改AllowRemoteConnection=1,Port=42424s

WebLibrary.dll 源码 (转s)

View Code
using System.Web;
using System;
using System.Configuration;
using System.Diagnostics;
using System.Reflection;
using System.Web.SessionState;

namespace WebLibrary
{
public class CrossDomainCookie : IHttpModule
{
private string m_RootDomain = string.Empty;

#region IHttpModule Members

public void Dispose()
{

}

public void Init(HttpApplication context)
{
m_RootDomain
= ConfigurationManager.AppSettings["RootDomain"];

Type stateServerSessionProvider
= typeof(HttpSessionState).Assembly.GetType

(
"System.Web.SessionState.OutOfProcSessionStateStore");
FieldInfo uriField
= stateServerSessionProvider.GetField("s_uribase", BindingFlags.Static | BindingFlags.NonPublic);

if(uriField == null)
thrownewArgumentException(
"UriField was not found");

uriField.SetValue(
null, m_RootDomain);

context.EndRequest
+= newSystem.EventHandler(context_EndRequest);
}

void context_EndRequest(object sender, System.EventArgs e)
{
HttpApplication app
= sender as HttpApplication;

for(inti = 0; i < app.Context.Response.Cookies.Count; i++)
{
app.Context.Response.Cookies[i].Domain
= m_RootDomain;
}
}

#endregion
}
}

第一次写博客,不对之处请大家拍板!

posted @ 2011-08-04 18:21  坚持枪手  阅读(422)  评论(0)    收藏  举报