如何压缩asp.net产生的viewstate
1. 在网站的app_code目录下面增加一个文件 ViewStateHelper.cs
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
using System.IO.Compression;
/// <summary>
///ViewStateHelper 的摘要说明
/// </summary>
public class ViewStateHelper
{
public ViewStateHelper()
{
//
//TODO: 在此处添加构造函数逻辑
//
}
public static byte[] Compress(byte[] data)
{
MemoryStream ms = new MemoryStream();
GZipStream stream = new GZipStream(ms, CompressionMode.Compress);
stream.Write(data, 0, data.Length);
stream.Close();
return ms.ToArray();
}
public static byte[] Decompress(byte[] data)
{
MemoryStream ms = new MemoryStream();
ms.Write(data, 0, data.Length);
ms.Position = 0;
GZipStream stream = new GZipStream(ms, CompressionMode.Decompress);
MemoryStream temp = new MemoryStream();
byte[] buffer = new byte[1024];
while (true)
{
int read = stream.Read(buffer, 0, buffer.Length);
if (read <= 0)
{
break;
}
else
{
temp.Write(buffer, 0, buffer.Length);
}
}
stream.Close();
return temp.ToArray();
}
}
2. 在需要压缩viewastate 的网页的后台文件里面增加代码
protected override void SavePageStateToPersistenceMedium(object state)
{
LosFormatter formatter = new LosFormatter();
StringWriter writer = new StringWriter();
formatter.Serialize(writer, state);
string viewState = writer.ToString();
byte[] data = Convert.FromBase64String(viewState);
byte[] compressedData = ViewStateHelper.Compress(data);
string str = Convert.ToBase64String(compressedData);
ClientScript.RegisterHiddenField(" __MYVIEWSTATE ", str);
}
protected override object LoadPageStateFromPersistenceMedium()
{
string viewstate = Request.Form[" __MYVIEWSTATE "];
byte[] data = Convert.FromBase64String(viewstate);
byte[] uncompressedData =
ViewStateHelper.Decompress(data);
string str = Convert.ToBase64String(uncompressedData);
LosFormatter formatter = new LosFormatter();
return formatter.Deserialize(str);
}