您的位置:首页 > 编程语言 > ASP

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

2012-07-19 18:01 274 查看
原文地址:http://www.itivy.com/ivy/archive/2011/4/24/634392360221984930.html

新建一个类库项目,添加以下类:

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)
throw new ArgumentException("UriField was not found");

uriField.SetValue(null, m_RootDomain);

context.EndRequest += new System.EventHandler(context_EndRequest);
}
void context_EndRequest(object sender, System.EventArgs e)
{
HttpApplication app = sender as HttpApplication;
for (int i = 0; i < app.Context.Response.Cookies.Count; i++)
{
app.Context.Response.Cookies[i].Domain = m_RootDomain;
}
}
#endregion
}
}

把它编译成dll。

然后在每个需要共享session的网站项目中做以下几件事情:

1、引用上面的dll

2、在web.config的appsetting节点中添加你的主站域名

<add key="RootDomain" value=".itivy.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=127.0.0.1:42424" timeout="30" />

5、在web.config的system.webServer几点中添加

<modules>
<add name="CrossDomainCookieModule" preCondition="managedHandler" type="WebLibrary.CrossDomainCookie, WebLibrary"/>
</modules>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: