压缩视图状态是添加另一个与__VIEWSTATE具有相同ID的隐藏字段

时间:2013-10-12 08:20:02

标签: asp.net viewstate

我正在尝试压缩ASP.Net 4.0中的viewstate,因此页面加载速度更快,非常臃肿的viewstate页面。

但是,当我在浏览器中查看页面源时,我发现了2个隐藏字段,其名称和ID都是“__VIEWSTATE”。

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

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

enter image description here

1 个答案:

答案 0 :(得分:0)

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

public class 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();
}
}

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

     public partial class Default : PageCompressed