Have you ever wondered what is actually encoded in the __VIEWSTATE hidden variable on your WebForms? It’s actually a base64 serialized encoding of a datatype called a Triplet, that has other objects nested within it. I threw together a small class that has a single static method that will write the ViewState to a file. It intends to see the hierarchy. It also deserializes the ViewState into a Triplet object that you can view in the debugger. This code is only for debugging, and should not be left in the shipping application.
Call the method in the Page_Load
event of your Web Form, like this:
DebugViewState.SeeViewState(Request.Form["__VIEWSTATE"], @"c:\temp\viewstate.txt");
And include this class in the project:
using System;
using System.Diagnostics;
using System.Web.UI;
public class DebugViewState
{
// Written by Greg Reddick. http://www.xoc.net
public static void SeeViewState(string strViewState, string strFilename)
{
if (strViewState != null)
{
Debug.Listeners.Clear();
System.IO.File.Delete(strFilename);
Debug.Listeners.Add(new TextWriterTraceListener(strFilename));
string strViewStateDecoded =
(new System.Text.UTF8Encoding()).
GetString(Convert.FromBase64String(strViewState));
string[] astrDecoded = strViewStateDecoded.Replace("<", "<\n").Replace(">", "\n>").Replace(";", ";\n").Split('\n');
Debug.IndentSize = 4;
foreach (string str in astrDecoded)
if (str.Length > 0)
if (str.EndsWith(@"\<")) Debug.Write(str);
else if (str.EndsWith(@"\")) Debug.Write(str);
else if (str.EndsWith("<")) { Debug.WriteLine(str); Debug.Indent(); }
else if (str.StartsWith(">;") || str.StartsWith(">"))
{
Debug.Unindent();
Debug.WriteLine(str);
}
else if (str.EndsWith(@"\;"))
Debug.Write(str);
else
Debug.WriteLine(str);
Debug.Close();
Debug.Listeners.Clear();
//Get into the debugger after executing this line to see how .NET looks
//at
//the ViewState info. Compare it to the text file produced above.
Triplet trp = (Triplet)((new LosFormatter()).Deserialize(strViewState));
}
}
}