日期:2010-05-02  浏览次数:20551 次

服务器端控件带来的好外我在这就不多说了,但多过的使用服务器端件保存控件的状态会带来大量的ViewState的情况大家一定遇到过吧.过多的ViewState会很大程度上降低页面的加载速度制成服务器端的性能下降.

以下是结合CSharpZipLib对ViewState进行压缩的方法.

MSPlus.Web.UI.Page 源码:
using System;
using System.Web.UI;
using System.IO;
using ICSharpCode.SharpZipLib.Zip.Compression;

namespace MSPlus.Web.UI
{
    /**//// <summary>
    /// 压缩ViewState By Mack.Z (MSPlus)
    /// </summary>
    public class Page : System.Web.UI.Page
    {

        protected override void SavePageStateToPersistenceMedium(Object pViewState)
        {
            LosFormatter mFormat = new LosFormatter();
            StringWriter mWriter = new StringWriter();

            mFormat.Serialize(mWriter, pViewState);
            String mViewStateStr = mWriter.ToString();

            byte[] pBytes = System.Convert.FromBase64String(mViewStateStr);

            pBytes = Compress(pBytes);

            String vStateStr = System.Convert.ToBase64String(pBytes);

            RegisterHiddenField("__MSPVSTATE", vStateStr);
        }

        protected override Object LoadPageStateFromPersistenceMedium()
        {
            String vState = this.Request.Form.Get("__MSPVSTATE");

            byte[] pBytes = System.Convert.FromBase64String(vState);

            pBytes = DeCompress(pBytes);

            LosFormatter mFormat = new LosFormatter();

            return mFormat.Deserialize(System.Convert.ToBase64String(pBytes));
        }


        public static byte[] Compress(byte[] pBytes)
        {
            MemoryStream mMemory = new MemoryStream();

            Deflater mDeflater = new Deflater(ICSharpCode.SharpZipLib.Zip.Compression.Deflater.BEST_COMPRESSION);
            ICSharpCode.SharpZipLib.Zip.Compression.Streams.DeflaterOutputStream mStream = new ICSharpCode.SharpZipLib.Zip.Compression.Streams.DeflaterOutputStream(mMemory,mDeflater,131072);

            mStream.Write(pBytes,0,pBytes.Length);
            mStream.Close();

            return mMemory.ToArray();