I will not talk about the advantages of the server-side controls here, but the usage of the server-side component to save the control status will bring about a large number of viewstates. too many viewstates will greatly reduce the page loading speed and reduce the server performance.
The following describes how to compress ViewState with CSharpZipLib.
MSPlus. Web. UI. Page source code: using System;
Using System. Web. UI;
Using System. IO;
Using ICSharpCode. SharpZipLib. Zip. Compression;
Namespace MSPlus. Web. UI
{
/** // <Summary>
/// Compress 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 ();
}
}
}
Usage (ASPX. CS Page inherits MSPlus. Web. UI. Page ):Public class PageClass: System. Web. UI. Page
Test result: the compressed ViewState is only the original20%!
I made a simple test. First, I updated the page to view the CPU usage of w3wp.exe. The ViewState on this page is 3.996 Bytes.
Below w3wp.exe is the CPU usage for each refresh
05 03 05 03 06 05 08 03 05 03 not encrypted, average is 4.6
05 05 06 05 03 08 02 03 05 06 encryption, with an average of 5.3