Getting asp.net to store viewstate in the session rather than bulking up the html

Chris picture Chris · Jan 7, 2011 · Viewed 7.6k times · Source

I'm trying to get asp.net to store viewstate in the session rather than bulking up the html.

Now i've read that asp.net comes with the SessionPageStatePersister which can be used instead of the default HiddenFieldPageStatePersister to do this. I was wondering how i go about dropping it in?

This is what i've got so far: I think i need to create a PageAdapter that returns a SessionPageStatePersister from its GetStatePersister method, and somehow get the page to use this pageadapter. But Page.PageAdapter only has a getter, so i'm not sure how you set it.

See the 'remarks' heading here: http://msdn.microsoft.com/en-us/library/system.web.ui.hiddenfieldpagestatepersister.aspx

Thanks!

Answer

blowdart picture blowdart · Jan 7, 2011

You sure you want to do this? There are problems

  1. How do you keep individual pages apart? Sure, you can prefix the session state name with the page, eg. Session["/default.aspx-Viewstate"] but what happens when the user has multiple instances of a page open?
  2. So to solve that you put a hidden field with, say, a GUID in each page, which you then use as a key. So your session size grows. And grows. And grows. How will you know if/when you can remove things safely?

If you insist on heading down this read then all you need to do is derive a class from page and override LoadPageStateFromPersistenceMedium() and SavePageStateToPersistenceMedium(). But you'll hate yourself and rip it out eventually.

Just make sure you have HTTP compression turned on at your server, and please, worry about something else instead.