asp.net Session 共享

本文探讨了如何使用自定义HttpModule实现跨域资源共享,包括设置根域名、修改Cookie Domain属性,确保Cookie能在所有二级域名下共享。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

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

namespace Ks5uCMS.Web.UI
{
    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;
            string cookieName = System.Web.Security.FormsAuthentication.FormsCookieName;
            HttpCookie cookie = app.Context.Response.Cookies[cookieName];
            if (cookie != null)
            {
                //将Cookie的Domain更改为.cnblogs.com
                //这样就使Cookie能共享于所有的二级域名
                cookie.Domain = m_RootDomain;

            }


            //for (int i = 0; i < app.Context.Response.Cookies.Count; i++)
            //{
            //    if (app.Context.Response.Cookies[i].Name == "ASP.NET_SessionId")
            //    { app.Context.Response.Cookies[i].Domain = m_RootDomain; }
            //}
        }

        #endregion
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值