ASP.NET通过序列化机制实现对Session共享[Session序列化一]

作者: unvs 分类: ASP.NET 发布时间: 2011-12-14 21:36 ė14,777 views 6没有评论

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

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

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

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

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

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

using System;
using System.Data;
using System.Configuration;
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;
using System.Collections;
using System.IO;
using System.Runtime.Serialization.Formatters.Soap;
using System.Runtime.Serialization.Formatters.Binary;

[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;
    }

}
/// <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 + g
uid + ".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;
        }
    }
}

编译项目,生成ShareSession.dll

把ShareSession.dll引入 你需要共享的站点 配置web.config

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

在Web Server 1上的应用程序中新建一个页面,功能是初始化Session,然后把Session信息序列化,代码如下:<a href="另一站点地址.aspx?AUTH_GUID=<%=AUTH_GUID %>">Go Other Web Site</a>

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

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

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

    protected void Page_Load(object sender, EventArgs e)
    {
        string guid = Request.Params["AUTH_GUID"].ToString();
        ShareSessionFormatter.Deserialize(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 />");

    }

然后只需要在程序中再判断一下,session过期时间然后及时清理文件夹里的.XML文件,并维护好session安全问题就可以了。

此文转载自百度空间:http://hi.baidu.com/yandavid/blog/item/a64a87518da4772242a75b85.html

本博文章基本上属于原创或收集整理,都是心血结晶。
欢迎转载分享,转载请注明出处,谢谢!
本文地址:ASP.NET通过序列化机制实现对Session共享[Session序列化一]

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Ɣ回顶部