0

我正在尝试在 ASP.Net 4.0 中压缩视图状态,因此对于严重臃肿的视图状态页面,页面加载速度更快。

但是,当我在浏览器中查看页面源时,我发现 2 个隐藏字段具有相同的名称和 '__VIEWSTATE' 的 ID。

我的代码如下。如何压缩视图状态但让它存储在其原始隐藏字段中而不创建另一个重复的隐藏字段?

protected override void SavePageStateToPersistenceMedium(object viewState)
{
    byte[] viewStateArray;
    using (MemoryStream memoryStream = new MemoryStream())
    {
        _objectStateFormatter.Serialize(memoryStream, viewState);
        viewStateArray = memoryStream.ToArray();
    }
    ClientScript.RegisterHiddenField("__VIEWSTATE",
                 Convert.ToBase64String(GZip.Compress(viewStateArray)));
}

在此处输入图像描述

4

1 回答 1

0
using System.IO;
using System.IO.Compression;
using System.Web.UI;

公共类 PageCompressed : System.Web.UI.Page {

private ObjectStateFormatter _formatter = new ObjectStateFormatter();
protected override void SavePageStateToPersistenceMedium(object viewState)
{
    MemoryStream ms = new MemoryStream();
    _formatter.Serialize(ms, viewState);
    byte[] viewStateArray = ms.ToArray();
    ClientScript.RegisterHiddenField("__CVIEWSTATE", Convert.ToBase64String(_Compress(viewStateArray)));
}
protected override object LoadPageStateFromPersistenceMedium()
{
    string vsString = Request.Form["__CVIEWSTATE"];
    byte[] bytes = Convert.FromBase64String(vsString);
    bytes = _DeCompress(bytes);
    return _formatter.Deserialize(Convert.ToBase64String(bytes));
}

private byte[] _Compress(byte[] inputBytes)
{
    MemoryStream m = new MemoryStream();
    GZipStream zip = new GZipStream(m, CompressionMode.Compress, true);
    zip.Write(inputBytes, 0, inputBytes.Length);
    zip.Close();
    return m.ToArray();
}
private byte[] _DeCompress(byte[] inputBytes)
{
    MemoryStream m = new MemoryStream(inputBytes);
    MemoryStream mout = new MemoryStream();
    GZipStream zip = new GZipStream(m, CompressionMode.Decompress, true);
    do
    {
        byte[] bBuffer = new byte[4097];
        int iRead = zip.Read(bBuffer, 0, bBuffer.Length);
        if (iRead > 0)
        {
            mout.Write(bBuffer, 0, iRead);
        }
        else
        {
            break; 
        }
    } while (true);
    zip.Close();
    return mout.ToArray();
}
}

您可以使用此接口类来压缩视图状态,方法是在每个页面的代码中像这样继承它

     公共部分类默认值:PageCompressed
于 2013-11-18T07:11:32.490 回答