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 the deflateAlgorithmThe method and attributes of compressing and extracting streams.
Gzipstream provides methods and attributes for compressing and extracting streams.
In the following demoCodeIn, we create a viewstatecompression class that contains two methods and returns byte [] data:
1. gzipstream compression/Decompression
Using System; Using System. Collections. Generic; Using System. LINQ; Using System. Web; Using System. IO; Using System. Io. compression; /// <Summary> /// Summary of viewstatecompression /// </Summary> Public Class Viewstatecompression { Public Viewstatecompression (){ // // Todo: add the 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:
Using System; Using System. Collections. Generic; Using System. LINQ; Using System. Web; Using System. IO; Using System. Web. UI; /// <Summary> /// Basepage Summary /// </Summary> Public Class Basepage: system. Web. UI. Page { Public Basepage (){ // // Todo: add the constructor logic here // } Protected Override Void Savepagestatetopersistencemedium ( 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 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:
Using System; Using System. Collections. Generic; Using System. LINQ; Using System. Web; Using System. IO; Using System. Web. UI; /// <Summary> /// Basepage Summary /// </Summary> Public Class Basepage: system. Web. UI. Page { Public Basepage (){ // // Todo: add the constructor logic here // } 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 {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: