压缩ASP.NET中的ViewState
摘要:文章:压缩ASP.NET中的ViewState 摘要:服务器端控件带来的好外我在这就不多说了,但多过的使用服务器端件保存控件的状态会带来大量的ViewState的情况大家一定,发表于北京联高软件有限公司技术文章栏目,代码以高亮显示。
关键字:压缩, viewstate, pbytes, new, system, compression, string, mstream, mmemory, web, icsharpcode, ui, sharpziplib, page
服务器端控件带来的好外我在这就不多说了,但多过的使用服务器端件保存控件的状态会带来大量的ViewState的情况大家一定遇到过吧.过多的ViewState会很大程度上降低页面的加载速度制成服务器端的性能下降.
以下是结合CSharpZipLib对ViewState进行压缩的方法.
MSPlus.Web.UI.Page 源码:
using System; using System.Web.UI; using System.IO; using ICSharpCode.SharpZipLib.Zip.Compression; namespace MSPlus.Web.UI { /**//// <summary> /// 压缩ViewState By Mack.Z (MSPlus) /// </summary> public class Page : System.Web.UI.Page { protected override void SavePageStateToPersistenceMedium(Object pViewState) { LosFormatter mFormat = new LosFormatter(); StringWriter mWriter = new StringWriter(); mFormat.Serialize(mWriter, pViewState); String mViewStateStr = mWriter.ToString(); byte[] pBytes = System.Convert.FromBase64String(mViewStateStr); pBytes = Compress(pBytes); String vStateStr = System.Convert.ToBase64String(pBytes); RegisterHiddenField("__MSPVSTATE", vStateStr); } protected override Object LoadPageStateFromPersistenceMedium() { String vState = this.Request.Form.Get("__MSPVSTATE"); byte[] pBytes = System.Convert.FromBase64String(vState); pBytes = DeCompress(pBytes); LosFormatter mFormat = new LosFormatter(); return mFormat.Deserialize(System.Convert.ToBase64String(pBytes)); } public static byte[] Compress(byte[] pBytes) { MemoryStream mMemory = new MemoryStream(); Deflater mDeflater = new Deflater(ICSharpCode.SharpZipLib.Zip.Compression.Deflater.BEST_COMPRESSION); ICSharpCode.SharpZipLib.Zip.Compression.Streams.DeflaterOutputStream mStream = new ICSharpCode.SharpZipLib.Zip.Compression.Streams.DeflaterOutputStream(mMemory,mDeflater,131072); mStream.Write(pBytes,0,pBytes.Length); mStream.Close(); return mMemory.ToArray(); } public static byte[] DeCompress(byte[] pBytes) { ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream mStream = new ICSharpCode.SharpZipLib.Zip.Compression.Streams.InflaterInputStream(new MemoryStream(pBytes)); MemoryStream mMemory = new MemoryStream(); Int32 mSize; byte[] mWriteData = new byte[4096]; while(true) { mSize = mStream.Read(mWriteData, 0, mWriteData.Length); if (mSize > 0) { mMemory.Write(mWriteData, 0, mSize); } else { break; } } mStream.Close(); return mMemory.ToArray(); } } }
使用方法(ASPX.CS页面继承MSPlus.Web.UI.Page):public class PageClass : System.Web.UI.Page
测试下来的结果:压缩后的ViewState只有原来的20%!
--------------------------------------------------------------------------------
我作了一个小小的测试.先后用同一个页面加密和不加密的情况下,刷新页面观测w3wp.exe的CPU占用情况.此页面的ViewState大小为3.996 Bytes
w3wp.exe 以下是每次刷新的时CPU的情况
05 03 05 03 06 05 05 08 03 05 03 不加密,平均是 4.6
05 05 06 05 05 03 08 02 03 05 06 加密,平均是5.3
转载自:http://www.legalsoft.com.cn/docs/895.html