asp.net 子应用程序/虚拟目录 session共享

最近遇到了一个问题,我做的asp.net mvc应用程序要作为一个子应用程序部署到几个站点中,需要在本应用程序中获取站点的session值。

已经使用了session state server,并设置了machine key,但还是不行。

这个问题折腾了整整一天的时间。网上有很多人遇到了这个问题,也有很多解决方案,但大都不能用。最后在某个英文站点中找到了解决的方法。

现将解决方法整理之后贴出来。

1.建立一个HttpModule

 /// <summary>
    /// 这个模块需要放到整个管道的前端
    /// </summary>
    public class SessionShareModule : IHttpModule
    {

        void IHttpModule.Init(HttpApplication context)
        {
            Type storeProvider = typeof(HttpSessionState).Assembly.GetType("System.Web.SessionState.OutOfProcSessionStateStore");

            FieldInfo uriField = storeProvider.GetField("s_uribase", BindingFlags.Static | BindingFlags.NonPublic);

            if (uriField == null)
            {
                throw new ArgumentException("UriField was not found");
            }

            uriField.SetValue(null, "xxx.cn");

            context.EndRequest += new EventHandler(this.EndRequest);
        }



        /// <summary>
        /// 在请求结束之后,将所有的cookie的域都改写为 xxx.cn
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        void EndRequest(object sender, EventArgs args)
        {
            HttpApplication application = sender as HttpApplication;

            for (int i = 0; i < application.Response.Cookies.Count; i++)
            {
                application.Response.Cookies[i].Domain = "xxx.cn";
            }
        }



        void IHttpModule.Dispose()
        {

        }
    }

模块部署

(1)将这个模块的dll文件复制到站点和子应用程序的bin目录下

(2)在站点的web.config的  <system.webServer> <modules>节下添加配置:

   <add name="SessionShare" type="XXX.SessionShare.SessionShareModule, XXX.SessionShare" />

子应用程序的web.config配置项可加可不加。不加的话,它会继承站点的配置项。加的话,它会覆盖站点的配置项。建议不用加。

 

posted @ 2015-12-03 20:07  何德海  阅读(1814)  评论(0编辑  收藏  举报