Compress Viewstate

In ASP.NET we can compress viewstate of the page, with the help of System.IO.Compression namespace.

With the help of GZipStream class we can reduce the size of viewstate of the page.

The following class contains two methods for compressing and decompressing a stream.

using System;
using System.Data;
using System.Configuration;
using System.IO;
using System.IO.Compression;

public static class CompressViewState
{
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();
}

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();
}
}

In order to compress the ViewState of a web page, you have to override the two methods LoadPageStateFromPersistenceMedium and SavePageStateToPersistenceMedium.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
private ObjectStateFormatter _formatter = new ObjectStateFormatter();

protected override void SavePageStateToPersistenceMedium(object viewState)
{
MemoryStream ms = new MemoryStream();
_formatter.Serialize(ms, viewState);
byte[] viewStateArray = ms.ToArray();
ClientScript.RegisterHiddenField("__VSTATE", Convert.ToBase64String(CompressViewState.Compress( viewStateArray)));
}

protected override object LoadPageStateFromPersistenceMedium()
{
string vsString = Request.Form["__VSTATE"];
byte[] bytes = Convert.FromBase64String(vsString);
bytes = CompressViewState.Decompress(bytes);
return _formatter.Deserialize(Convert.ToBase64String(bytes));
}

}