分享:ViewState压缩方法
在使用 Asp.net WebForm进行开发中我一般会在自定义页面基类(BasePage)中进行ViewState的压缩, 注:此方法为网上收集,功能挺实用的。
压缩代码:
/// <summary> /// 压缩数据 /// </summary> /// <param name="data"></param> /// <returns></returns> public 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(); } /// <summary> /// 解压数据 /// </summary> /// <param name="data"></param> /// <returns></returns> public 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(); }
在页面的基类中的代码:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/// <summary> /// 重载SavePageStateToPersistenceMedium /// <remarks> /// 将viewstate进行压缩 /// </remarks> /// </summary> /// <param name="state"></param> 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 = this.Compress(data); string str = Convert.ToBase64String(compressedData); ClientScript.RegisterHiddenField("__MYVIEWSTATE", str); } /// <summary> /// 重载LoadPageStateFromPersistenceMedium /// <para>将viewstate进行解压缩</para> /// </summary> /// <returns></returns> protected override object LoadPageStateFromPersistenceMedium() { string viewstate = Request.Form["__MYVIEWSTATE"]; byte[] data = Convert.FromBase64String(viewstate); byte[] uncompressedData = this.Decompress(data); string str = Convert.ToBase64String(uncompressedData); LosFormatter formatter = new LosFormatter(); return formatter.Deserialize(str); }
代码比较简单,所以不写注释。
压缩效率可将Viewstate减小50%左右。(非精确值,估计的大概值);
上面代码我都写在BasePage基类中。
.......................................this is a good man