You can, with a little trickery, hijack just the serialization of the page state by deriving from System.Web.Page and override the PageStatePersister property:
private PageStatePersister _pageStatePersister = null;
protected override PageStatePersister PageStatePersister
{
get { return _pageStatePersister ?? (_pageStatePersister = new PersistState(this)); }
}
Once you've done this you can derive a new instance from HiddenFieldPageStatePersister and from there use reflection to change the persistence implementation:
class PersistState : HiddenFieldPageStatePersister, IStateFormatter
{
public PersistState(Page p) : base(p)
{
FieldInfo f = typeof(PageStatePersister).GetField("_stateFormatter", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.SetField);
f.SetValue(this, this);
}
object IStateFormatter.Deserialize(string serializedState)
{
BinaryFormatter f = new BinaryFormatter();
using (GZipStream gz = new GZipStream(new MemoryStream(Convert.FromBase64String(serializedState)), CompressionMode.Decompress, false))
return f.Deserialize(gz);
}
string IStateFormatter.Serialize(object state)
{
BinaryFormatter f = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
using (GZipStream gz = new GZipStream(ms, CompressionMode.Compress, true))
f.Serialize(gz, state);
return Convert.ToBase64String(ms.ToArray());
}
}
}
BEWARE
This is an example only for exploratory purposes. The above code IS A SECURITY RISK as it does not sign and encrypt the payload and therefore can easily be hacked by anyone attempting to do your site harm.
Again DO NOT USE THIS CODE without a full and complete understanding of security, cryptography, and .Net serialization.
</warning>
The real problem, as other have said, is the use of page state to begin with. The easiest solution to a poorly written ASP.NET app that makes heavy use of page state is to stand up a state server and use the SessionPageStatePersister.