伺服器端控制項帶來的好外我在這就不多說了,但多過的使用伺服器端件儲存控制項的狀態會帶來大量的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