Just a first stab at this, uses some classes I used in another project (I'll attribute the compression code later...I believe I got it from the Sharpziplib stuff - with some modifications - I'll stick the comment headers back in to comply with the Licensing stuff later - right now consider it an example only) the actual code to compress the viewstate is VERY simple:
using System;
using System.Web.UI;
using System.IO;
namespace ViewStateCompression
{
///
/// Summary description for CompressedVSBasePage.
///
public class CompressedVSBasePage :System.Web.UI.Page
{
private LosFormatter _formatter = new LosFormatter();
protected override void SavePageStateToPersistenceMedium(object viewState)
{
StringWriter sw = new StringWriter();
_formatter.Serialize(sw, viewState);
ComDePress cmp = new ComDePress();
string outStr = cmp.Compress(sw.ToString());
Page.RegisterHiddenField("__COMPRESSEDVIEWSTATE",outStr);
}
protected override object LoadPageStateFromPersistenceMedium()
{
string vsString = Request.Form["__COMPRESSEDVIEWSTATE"];
string outStr = new ComDePress().DeCompress(vsString);
return _formatter.Deserialize(outStr);
}
}
}
To use it, just inherit from this page instead of the normal System.Web.UI.Page. Obviously you lose some of the normal Viewstate functions such as encryption - but these should be easy to slot back in...I am currently seeing pretty large savings in ViewState size from using this - using BZip2 compression - as it's a piece of code I had lying about..., please try it out. Any comments / suggestions are, as always, appreciated.
I've made a test project for playing with this , it's VS.NET 2003, it has everything required (including the compression stuff).
UPDATE: Just been doing some testing with this...as an example, using a DataSet populated from "Select * From Orders" of the Northwind DB bound onto a default DataGrid (I chose this to be the porkiest possible...), I go from 659984 bytes in my viewstate down to 52080 bytes...a saving of around 92% - which I think is pretty impressive! I'm sure there are some drawbacks to this (besides the few extra cycles required for the compression) - but is there any actual reason why MS does not give a compression option for ViewState out-of-the-box - anyone???
UPDATE: OK, for those who've been criticising the code...this is a PROTOTYPE - just to test the idea, I plan to play around with this a bit more at some point and will be looking at including some funky features like Denis Bauer's ViewState viewer built-in, different compression systems, different encryption - including the incredibly efficient Twofish- in short it will be a toy for me to look at and extend the current ViewState implementation.
© 2025 Scott Galloway — Unlicense — All content and source code on this site is free to use, copy, modify, and sell.