Override PageStatePersister to Eliminate ViewState

I was working on some legacy ASP.Net code recently. We were profiling performance and the key problem was wire performance because of ViewState. Our first idea was to eliminate use of ViewState but there were a lot of implicit dependencies inside of some complex data binding on a GridView control and time was short.

We were able to yield huge performance gains by overriding the PageStatePersister property of a key code-behind class. The change moves the state that would be serialized as great gobs of base64-encoded drek into Session so that it is stored in memory on the server. This isn’t a perfect solution because it increases the memory demand on the server. For this scenario, it was a good medium-term compromise that hugely improves performance over a slow WAN.

The PageStatePersister class and property on System.Web.UI.Page is “new” to ASP.Net 2.0+. It is an abstract class that is exposed as a PageStatePersister property in the code-behind. Microsoft ships two concrete implementations: HiddenFieldPageStatePersister and SessionPageStatePersister. The default is HiddenFieldPageStatePersister which emits base64 text to a hidden __VIEWSTATE input element in the rendered HTML. The SessionStatePersister puts the data in Session instead. It is there to help optimize the generated HTML for mobile browsers and low-bandwidth scenarios.

Here’s the code to do the switcheroo that puts the ViewState data into Session.

 * HACK: put the veiwstate into session instead of writing to page. Then the __ViewState will only contain the required
 * ControlState. This increases server memory consumption. A better long-term solution would be to rework the GridView
 * to work with ViewState disabled and put it inside of an UpdatePanel.
protected override PageStatePersister PageStatePersister
        return new SessionPageStatePersister( Page );

2 Responses to Override PageStatePersister to Eliminate ViewState

  1. {Angie says:

    Thanks Brian Reiter for the share

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: