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