Introduction to ASP. NET viewstate
ASP. NET viewstate is a new State service that allows developers to track the UI status based on each user. The 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. When the connection speed is slow, your response time will be slower. 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.
Download the sample project.
Aspnet_viewstate.rar 34kb.
Method 1: Use System. Io. Compression
System. Io. CompressionThe 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 //} // comprete 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 () ;}// decompress 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 ();}}}
1b. deflatestream compression/Decompression: Download the sample code in this article.
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 initialize (Object pageviewstate) {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 = new losformatter (); Return losformatter. deserialize (convert. tobase64string (B ));}}}
After the preceding 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 the first 100k, </form>. 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 overwrite the savepagestatetopersistencemedium () and loadpagestatefrompersistencemedium () methods by using the session method that allows 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 aggregate (Object pageviewstate) {memorystream MS = new memorystream (); losformatter m_formatter = new losformatter (); Aggregate (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 {viewstatebag = m_formatter.deserialize (convert. tobase64string (viewstatebytes);} catch (exception ex) {// log. insert ("Page viewtate is empty. "); viewstatebag = string. empty;} return viewstatebag ;}}}
After rewriting, we can see that viewstate is completely deleted and the data transmitted to the client is reduced from 1006b to 750b. This improves the performance of many data source controls on the page:
Download the sample project.
Aspnet_viewstate.rar 34kb.