Compressing the ViewState can improve web page response times on slower connections and reduce bandwidth usage, especially on pages with a lot of objects.
ViewState can be compressed automatically by replacing the ASP.NET Page class with a derived class we have called PageCompressed in the example below.
To use this new class, simply place it in your app_code folder and change the code behind class of each page to inherit PageCompressed instead of Page.
Imports System.IO
Imports System.IO.Compression
Public Class PageCompressed : Inherits System.Web.UI.Page
Private _formatter As New ObjectStateFormatter()
Protected Overloads Overrides Sub _
SavePageStateToPersistenceMedium(ByVal viewState As Object)
Dim ms As New MemoryStream()
_formatter.Serialize(ms, viewState)
Dim viewStateArray As Byte() = ms.ToArray()
ClientScript.RegisterHiddenField("__CVIEWSTATE", _
Convert.ToBase64String(_Compress(viewStateArray)))
End Sub
Protected Overloads Overrides Function _
LoadPageStateFromPersistenceMedium() As Object
Dim vsString As String = Request.Form("__CVIEWSTATE")
Dim bytes As Byte() = Convert.FromBase64String(vsString)
bytes = _DeCompress(bytes)
Return _formatter.Deserialize(Convert.ToBase64String(bytes))
End Function
Private Function _Compress(ByVal inputBytes() As Byte) As Byte()
Dim m As New MemoryStream()
Dim zip As New GZipStream(m, CompressionMode.Compress, True)
zip.Write(inputBytes, 0, inputBytes.Length)
zip.Close()
Return m.ToArray
End Function
Private Function _DeCompress(ByVal inputBytes() As Byte) As Byte()
Dim m As New MemoryStream(inputBytes)
Dim mout As New MemoryStream
Dim zip As New GZipStream(m, CompressionMode.Decompress, True)
Do
Dim bBuffer(4096) As Byte
Dim iRead As Integer = zip.Read(bBuffer, 0, bBuffer.Length)
If iRead > 0 Then
mout.Write(bBuffer, 0, iRead)
Else
Exit Do
End If
Loop
zip.Close()
Return mout.ToArray
End Function
End Class