Two Methods for compressing ViewState of Asp. Net performance

Source: Internet
Author: User

Asp.net ViewState is a new State service that allows developers to track the UI status based on each user. This auxiliary data is stored in a hidden field named _ VIEWSTATE.
Of course, ViewState has an important role in ASP. NET. If used properly, it can simplify page development and improve interaction between users and sites. If you ignore it, it can significantly increase the site response size and make your response time slower when the connection speed is slow. The browser will cause the ViewState to gradually increase the size of your page, resulting in performance problems. Therefore, the publication of ASP. NET 2.0 brings about some improvements to the ViewState mechanism, which makes ViewState easier to use and does not affect site performance. These improvements include reducing the number of codes, separating the travel status from the content into the status, and intelligently integrating data binding controls. You can solve this problem by disabling the control (EnableViewState = false) without maintaining the control status. However, it is necessary to maintain the control state in many cases, and the compressed ViewState helps improve the performance.
Method 1: Use System. IO. ComPRession
The System. IO. Compression namespace contains classes that provide basic stream Compression and decompression services.
This namespace contains two classes:
DeflateStream provides methods and attributes used to compress and decompress streams using the Deflate algorithm.
GZipStream provides methods and attributes for compressing and extracting streams.
In the Demo code below, we create a ViewStateCompression class, which contains two methods and returns byte [] data:
1. GZipStream compression/Decompression
Namespace ASPNET_ViewState.Code {
Public class ViewStateCompression {
Public ViewStateCompression (){
//
// TODO: Add constructor logic here
//
}
// Compression
Public static byte [] Compress (byte [] data ){
MemoryStream output = new MemoryStream ();
GZipStream gzip = new GZipStream (output,
CompressionMode. Compress, true );
Gzip. Write (data, 0, data. Length );
Gzip. Close ();
Return output. ToArray ();
}
// Extract
Public static byte [] Decompress (byte [] data ){
MemoryStream input = new MemoryStream ();
Input. Write (data, 0, data. Length );
Input. Position = 0;
GZipStream gzip = new GZipStream (input,
CompressionMode. Decompress, true );
MemoryStream output = new MemoryStream ();
Byte [] buff = new byte [64];
Int read =-1;
Read = gzip. Read (buff, 0, buff. Length );
While (read> 0 ){
Output. Write (buff, 0, read );
Read = gzip. Read (buff, 0, buff. Length );
}
Gzip. Close ();
Return output. ToArray ();
}
}
}
2. Execute the ViewStateCompression class
To use the ViewStateCompression compression and decompress Page ViewState function, we must rewrite the SavePageStateToPersistenceMedium () and LoadPageStateFromPersistenceMedium () methods of System. Web. UI. Page.
The SavePageStateToPersistenceMedium method can deserialize ViewState, which accepts parameters of a ViewState object.
The LoadPageStateFromPersistenceMedium method can serialize ViewState, which accepts a base64-encoded string parameter.
The following code is rewritten to create a BasePage class that inherits from System. Web. UI. Page:
Namespace ASPNET_ViewState.Code {
Public class BasePage: System. Web. UI. Page {
Public BasePage (){
}
Protected override void SavePageStateToPersistenceMedium (object pageViewState ){
LosFormatter losformatter = new LosFormatter ();
StringWriter sw = new StringWriter ();
Losformatter. Serialize (sw, pageViewState );
String viewStateString = sw. ToString ();
Byte [] B = Convert. FromBase64String (viewStateString );
B = ViewStateCompression. Compress (B );
// ---- ClientScript. RegisterHiddenField ("_ ZIPSTATE", Convert. ToBase64String (B ));
//
// Compatible with ASP. NET Ajax ViewState Compression
ScriptManager. RegisterHiddenField (this, "_ ZIPSTATE", Convert. ToBase64String (B ));
}
// Serialize ViewState
Protected override object LoadPageStateFromPersistenceMedium (){
String custState = Request. Form ["_ ZIPSTATE"];
Byte [] B = Convert. FromBase64String (custState );
B = ViewStateCompression. Decompress (B );
LosFormatter losformatter = new LosFormatter ();
Return losformatter. Deserialize (Convert. ToBase64String (B ));
}
}
}
After the above method, your ViewState may be reduced by 30-40%.
3. ViewState SEO
ViewState will affect SEO. Of course, the effect is not great. When searching a page, the search engine starts from the first character of the page source file to a location of KB. The following content is not very friendly and may even cause indexing problems. Therefore, we can consider moving the ViewState to the bottom of the page before kb. Please download the example in this article for reference code. Here is a reference:

 
Before moving:

 
After moving:


Method 2: Use session to completely delete ViewState
By using this method, ViewState can be completely deleted, and ViewState can be fully saved. It can also reduce the extra bytes required by the client to be downloaded, and the search engine can solve the indexing problem. The principle is to rewrite the SavePageStateToPersistenceMedium () and LoadPageStateFromPersistenceMedium () methods above by using Session to allow ViewState to be saved on the server.
The code after the above method is rewritten is as follows:
Namespace ASPNET_ViewState.Code {
Public class BasePage: System. Web. UI. Page {
Public BasePage (){
}
Protected override void SavePageStateToPersistenceMedium (object pageViewState ){
MemoryStream MS = new MemoryStream ();
LosFormatter m_formatter = new LosFormatter ();
M_formatter.Serialize (MS, pageViewState );
Ms. Position = 0;
StreamReader sr = new StreamReader (MS );
String viewStateString = sr. ReadToEnd ();
Byte [] ViewStateBytes = Convert. FromBase64String (viewStateString );
ViewStateBytes = ViewStateCompression. Compress (ViewStateBytes );
Session ["ViewState"] = Convert. ToBase64String (ViewStateBytes );
Ms. Close ();
Return;
}
// Serialize ViewState
Protected override object LoadPageStateFromPersistenceMedium (){
Object viewStateBag;
String m_viewState = (string) Session ["ViewState"];
Byte [] ViewStateBytes = Convert. FromBase64String (m_viewState );
ViewStateBytes = ViewStateCompression. Decompress (ViewStateBytes );
LosFormatter m_formatter = new LosFormatter ();
Try {
Vi

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.