| 网站首页 | 文章中心 | 电子书下载 | 矢量图库 | 在线视频教程 | 素材下载 | 程序代码下载 | 视频教程下载 | JS代码 | 论坛 | 
龙腾教程网  
常用软件类:
|杀毒安全 |联络聊天 |网络软件 |多媒体类 |系统工具 |图形图像 |系统工具 |应用软件 |行业软件
开发设计类:
|动画制作 |图像处理 |3D设计 |操作系统 |站长学院 |网络相关 |WEB设计 |数据库类 |程序开发
 
  您当前位置:您现在的位置: 龙腾软件教程网 >> 文章中心 >> WEB设计 >> asp.net >> asp.net技巧 >> 文章正文 
 
asp.net2.0实现跨站点共享Session解决方案
作者:未知 文章来源:网络
出处:http://blog.cafe-house.com/article.asp?id=44

我们在进行Web开发时经常会用到Session,用它去标识不同的会话,那么涉及到跨站点的时候如何实现Session共享呢?


通常的解决方案有:使用数据库、使用Cookies做中间桥等等。

下面介绍一种基于ASP.NET 2.0的,通过序列化和反序列化机制实现的一种解决方案。

首先看一下通常的服务器集群的网络拓扑结构:



利用序列化机制实现Session共享的原理:

1、Web Server 1的应用程序序列化Session信息为文本值(可以是Binary或Soap格式)

2、将序列化后的值写入文件,保存到File Server上

3、Web Server 2 对保存在File Server上的Session序列化后的值进行反序列化

4、在Web Server 2上重新构建Session值


下面我们来详细看看实现代码,分以下几个步骤:


1、创建一个类库工程:ShareSession

引入以下的命名空间:

System.configuration
System.Runtime.Serialization.Formatters.Soap
System.Web

2、创建一个类:SessionEntity

代码如下:

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace ShareSession
...{
    /**//* *****************************
     *
     *  Author      :    Xiaojun Liu
     *  Create Date :    2007.11.09
     *  Description :
     *
     * *****************************
    */



    [Serializable]
    public class SessionEntity
    ...{            
        [NonSerialized]
        public string AUTH_GUID = "";

        private Hashtable _HtShareSession;

        public Hashtable HtShareSession
        ...{
            get
            ...{
                return this._HtShareSession;
            }
            set
            ...{
                this._HtShareSession = value;
            }
        }


        public SessionEntity(string guid)
        ...{
            this.AUTH_GUID = guid;
        }
        
    }//


}//



3、创建一个序列化、反序列化操作的类:ShareSessionFormatter

代码如下:

using System;
using System.Web;
using System.Data;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization.Formatters.Soap;
using System.Runtime.Serialization.Formatters.Binary;
using System.Collections;
using System.IO;

namespace ShareSession
...{

    /**//* *****************************
     *
     *  Author      :    Xiaojun Liu
     *  Create Date :    2007.11.09
     *  Description :
     *
     * *****************************
    */


    /**//// <summary>
    /// 格式化操作器
    /// </summary>
    public class ShareSessionFormatter
    ...{

        private static string _ShareSessionPath = System.Configuration.ConfigurationManager.AppSettings["ShareSessionPath"].ToString();
        
        /**//// <summary>
        /// 序列化格式器类型
        /// </summary>
        public enum FormatterType
        ...{
            Binary,
            Soap
        };

        /**//// <summary>
        /// 执行序列化
        /// </summary>
        /// <param name="formatterType">类型</param>
        public static void Serialize(FormatterType formatterType)
        ...{
            if (HttpContext.Current.Session["AUTH_GUID"] == null)
            ...{
                HttpContext.Current.Session["AUTH_GUID"] = Guid.NewGuid().ToString();
            }
            Hashtable ht = new Hashtable();

            //遍历Session          
            foreach (string key in HttpContext.Current.Session.Contents.Keys)
            ...{
                ht.Add(key, HttpContext.Current.Session[key]);
            }                

            /**/////执行序列化
            switch (formatterType)
            ...{
                case FormatterType.Binary:
                    BinarySerialize(ht);
                    break;
                case FormatterType.Soap:
                    SoapSerialize(ht);
                    break;
                default:
                    break;
            }

        }

        /**//// <summary>
        /// 按照Binary格式序列化
        /// </summary>
        /// <param name="ht"></param>
        private static void BinarySerialize(Hashtable ht)
        ...{
            string guid = HttpContext.Current.Session["AUTH_GUID"].ToString();
            SessionEntity obj = new SessionEntity(guid);
            obj.HtShareSession = ht;
          
            // 创建一个文件guid.xml
            Stream stream = File.Open(_ShareSessionPath + guid + ".xml", FileMode.Create);
            BinaryFormatter formatter = new BinaryFormatter();

            //执行序列化
            formatter.Serialize(stream, obj);
            stream.Close();

            // 将对象置空
            obj = null;
        }

        /**//// <summary>
        /// 按照Soap格式序列化
        /// </summary>
        /// <param name="ht"></param>
        private static void SoapSerialize(Hashtable ht)
        ...{
            string guid = HttpContext.Current.Session["AUTH_GUID"].ToString();
            SessionEntity obj = new SessionEntity(guid);
            obj.HtShareSession = ht;

            // 创建一个文件guid.xml
            Stream stream = File.Open(_ShareSessionPath + guid + ".xml", FileMode.Create);
            SoapFormatter formatter = new SoapFormatter();

            //执行序列化
            formatter.Serialize(stream, obj);
            stream.Close();

            // 将对象置空
            obj = null;
        }


        /**//// <summary>
        /// 反序列化
        /// </summary>
        /// <param name="formatterType">传送端的Session["AUTH_GUID"]</param>
        /// <param name="guid"></param>
        public static void Deserialize(FormatterType formatterType, string guid)
        ...{
            switch (formatterType)
            ...{
                case FormatterType.Binary:
                    BinaryDeserialize(guid);
                    break;
                case FormatterType.Soap:
                    SoapDeserialize(guid);
                    break;
                default:
                    break;
            }
        }


        /**//// <summary>
        /// 以Binary方式反序列化
        /// </summary>
        private static void BinaryDeserialize(string guid)
        ...{
            SessionEntity obj = new SessionEntity(guid);

            // 打开文件guid.xml
            Stream stream = File.Open(_ShareSessionPath + guid + ".xml", FileMode.Open);
            BinaryFormatter formatter = new BinaryFormatter();

            obj = (SessionEntity)formatter.Deserialize(stream);
            stream.Close();

            Hashtable ht = obj.HtShareSession;
            obj = null;

            //遍历ht,生成Session
            CreateSession(ht);
        }

        /**//// <summary>
        /// 以Soap方式反序列化
        /// </summary>
        private static void SoapDeserialize(string guid)
        ...{
            SessionEntity obj = new SessionEntity(guid);

            // 打开文件guid.xml
            Stream stream = File.Open(_ShareSessionPath + guid + ".xml", FileMode.Open);
            SoapFormatter formatter = new SoapFormatter();

            obj = (SessionEntity)formatter.Deserialize(stream);
            stream.Close();

            Hashtable ht = obj.HtShareSession;
            obj = null;

            //遍历ht,生成Session
            CreateSession(ht);
        }

        /**//// <summary>
        /// 遍历Hashtable,同时创建Session
        /// </summary>
        /// <param name="ht"></param>
        private static void CreateSession(Hashtable ht)
        ...{
            foreach (DictionaryEntry de in ht)
            ...{
                HttpContext.Current.Session[de.Key.ToString()] = de.Value;
            }
        }
        
        
    }//
}//



4、编译项目,生成ShareSession.dll

5、把ShareSession.dll引入Web Server 1上的应用程序中,同时在Web.config文件中增加配置字节

代码如下:

<!-- Session信息序列化后保存路径 -->
        <add key="ShareSessionPath" value="C:\ShareSession\"/>


6、在Web Server 1上的应用程序中新建一个页面,功能是初始化Session,然后把Session信息序列化,代码如下:


前台代码:

<%...@ Page Language="C#" AutoEventWireup="true" CodeFile="ShareSession.aspx.cs" Inherits="Front_Test_ShareSession" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Session共享</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Label ID="lHttp_Cookie" runat="server" Text=""></asp:Label>
            <a href="http://localhost:5000/Front/Test/ShareSession.aspx?AUTH_GUID=<%=AUTH_GUID %>">Go Other Web Site(port:5000)</a>
        </div>
    </form>
</body>
</html>

后台代码:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Front_Test_ShareSession : System.Web.UI.Page
...{
    public string AUTH_GUID = "";

    protected void Page_Load(object sender, EventArgs e)
    ...{
        Session.Clear();
        Session.Abandon();
        Session.Add("USER_ID", "2002");
        Session.Add("USER_NAME", "Xiaojun Liu");

        ShareSession.ShareSessionFormatter.Serialize(ShareSession.ShareSessionFormatter.FormatterType.Soap);
        AUTH_GUID = Session["AUTH_GUID"].ToString();

        
    }
}



7、在Web Server 2上进行第5步操作

8、在Web Server 2上的应用程序中新建一个页面,功能是反序列化,还原Session,同时读取Session信息进行测试,代码如下:

前台代码:

<%...@ Page Language="C#" AutoEventWireup="true" CodeFile="ShareSession.aspx.cs" Inherits="Front_Test_ShareSession" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Session共享</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Label ID="lHttp_Cookie" runat="server" Text=""></asp:Label>
        </div>
    </form>
</body>
</html>

后台代码:

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Front_Test_ShareSession : System.Web.UI.Page
...{
    protected void Page_Load(object sender, EventArgs e)
    ...{
        string guid = Request.Params["AUTH_GUID"].ToString();
        ShareSession.ShareSessionFormatter.Deserialize(ShareSession.ShareSessionFormatter.FormatterType.Soap,guid);

        Response.Write("USER_ID = "+Session["USER_ID"].ToString()+"<br />");
        Response.Write("USER_NAME = "+Session["USER_NAME"].ToString()+"<br />");
        Response.Write("AUTH_GUID = " + Session["AUTH_GUID"].ToString() + "<br />");
    }
}



此例子只是提供了一种解决思路,在应用过程中应根据项目不同进行调整及详细设计。
上一篇:
  • 上一篇文章:
  • 下一篇
  • 下一篇文章: 没有了
  • 收藏此文到百度搜藏 百度搜藏| 新浪VIvi| 365key| Younote| 博采中心| 你好BLOG| 亿友网摘| 和讯网摘|
    相关文章    
    .Net开发命名空间的命名规则
    ASP.NET2.0+SQL Server2005多层架构的应用
    Asp.net多层架构中的变量引用与传递
    ASP.NET 2.0轻松实现数据库应用开发
    ASP.NET实现DropDownList控件数据绑定第一项
    ASP.NET2.0 超强文本编辑器FCKeditor安装使
    ASP.NET编程中常用的函数集介绍
    Asp.net实现RAR压缩解压缩文件技巧
    asp.net 2.0中扩展login控件
    ASP.NET2.0利用PagedDataSource类实现DataL
     
     
     
    最新文章
    普通文章 asp.net2.0实现跨站点共享Sessio最新文章
    普通文章 .Net开发命名空间的命名规则最新文章
    普通文章 SQLServer数据库迁向的两种方法详最新文章
    普通文章 SQL Server数据库用户权限安全配最新文章
    普通文章 Photoshop绘制3D效果的按钮图标最新文章
    普通文章 黑客入侵WindowsXP常用的七种方法最新文章
    普通文章 Photoshop绘制甜美的巧克力甜心最新文章
    普通文章 FLASH制作中秋节饼大游行贺卡最新文章
    普通文章 Photoshop绘制古典木质风格屏风最新文章
    普通文章 Photoshop照片美化技巧-制作清幽最新文章
     
    热门文章
    推荐文章 Photoshop绘制羊皮卷轴地图
     
     
    设为首页 | 加入收藏 | 联系站长 | 友情链接 | 版权申明 

    版权所有2006-2008 龙腾教程网