Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the value of built, encoded ViewState?

Tags:

c#

asp.net

I need to grab the base64-encoded representation of the ViewState. Obviously, this would not be available until fairly late in the request lifecycle, which is OK.

For example, if the output of the page includes:

<input type="hidden" name="__VIEWSTATE"    id="__VIEWSTATE" value="/wEPDwUJODU0Njc5MD...==" /> 

I need a way on the server-side to get the value "/wEPDwUJODU0Njc5MD...=="

To clarify, I need this value when the page is being rendered, not on PostBack. e.g. I need to know the ViewState value that is being sent to the client, not the ViewState I'm getting back from them.

like image 647
Rex M Avatar asked Aug 04 '08 03:08

Rex M


People also ask

How do I decrypt ViewState?

Use Fiddler and grab the view state in the response and paste it into the bottom left text box then decode. For those using the current version of Fiddler (2.5. 1), the text box described in this answer can now be found by clicking the TextWizard option in the menu along the top (or Tools > TextWizard or Ctrl+E).

Where does ViewState value is stored?

By default, view state data is stored in the page in a hidden field and is encoded using base64 encoding. In addition, a hash of the view state data is created from the data by using a machine authentication code (MAC) key.

How is ViewState encoded?

ViewState is base64-encoded. It is not encrypted but it can be encrypted by setting EnableViewStatMAC=”true” & setting the machineKey validation type to 3DES.


2 Answers

Rex, I suspect a good place to start looking is solutions that compress the ViewState -- they're grabbing ViewState on the server before it's sent down to the client and gzipping it. That's exactly where you want to be.

  • Scott Hanselman on ViewState Compression (2005)
  • ViewState Compression with System.IO.Compression (2007)
like image 185
Jeff Atwood Avatar answered Sep 30 '22 10:09

Jeff Atwood


See this blog post where the author describes a method for overriding the default behavior for generating the ViewState and instead shows how to save it on the server Session object.

In ASP.NET 2.0, ViewState is saved by a descendant of PageStatePersister class. This class is an abstract class for saving and loading ViewsState and there are two implemented descendants of this class in .Net Framework, named HiddenFieldPageStatePersister and SessionPageStatePersister. By default HiddenFieldPageStatePersister is used to save/load ViewState information, but we can easily get the SessionPageStatePersister to work and save ViewState in Session object.

Although I did not test his code, it seems to show exactly what you want: a way to gain access to ViewState code while still on the server, before postback.

like image 24
Yaakov Ellis Avatar answered Sep 30 '22 10:09

Yaakov Ellis