ASP.NET: Seeing What is in the ViewState in ASP.NET Web Forms

Have you ever wondered what is actually encoded in the __VIEWSTATE hidden variable on your Web Forms? 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 indents 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.
    public static void SeeViewState(string strViewState, string strFilename)
        if (strViewState != null)
            Debug.Listeners.Add(new TextWriterTraceListener(strFilename));
            string strViewStateDecoded =
            (new System.Text.UTF8Encoding()).
            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(">"))
                    else if (str.EndsWith(@"\;"))

            //Get into the debugger after executing this line to see how .NET looks
            //the ViewState info. Compare it to the text file produced above.
            Triplet trp = (Triplet)((new LosFormatter()).Deserialize(strViewState));

No comments:

Post a Comment