Mike Cole
Mike Cole

Reputation: 14713

ASP.NET getting viewstate in global.asax

Is it possible to get at the viewstate in the global.asax file? I am having a problem with viewstate on some clients and I want to log what the viewstate is in the Application_Error event.

Upvotes: 4

Views: 2296

Answers (2)

kooch
kooch

Reputation: 107

I know this is a very old topic, but the answer to this question is a definite yes. Here is the easiest solution. In your page you need to capture the decrypted / deserialized viewstate in a session variable whenever there is an error. In your .aspx page, or in your base form if your pages all inherit from a common class add the following method:

public void Page_Error(object sender, EventArgs e)
{
     Session["ViewStateData"] = this.ViewState;
}

Then in your global.asax.cs class add this:

protected void Application_Error(object sender, EventArgs e)
{
   if (HttpContext.Current != null && HttpContext.Current.Session != null && HttpContext.Current.Session["ViewStateData] != null)
   {
      StringBuilder sbText = new StringBuilder();
      System.Web.UI.StateBag vs = (System.Web.UI.StateBag)HttpContext.Current.Session["ViewStateData"];
      sbText.Append("Viewstate Data:\r\n");
      foreach (string key in vs.Keys)
      {
         try
         {
            sbText.AppendFormat("{0}={1}\r\n", key, vs[key]);
         }
         catch (Exception)
         { }
      }

      HttpContext.Current.Session["ViewStateData"] = null;

   }
}

Note that vs[key] might be a complex object and thus you might need to add special handling for certain "key" values to write out it's properties, or add a custom ToString() override method to that object so that it writes out the information that you want to see.

Upvotes: 1

M4N
M4N

Reputation: 96571

The ViewState is posted to the server in a hidden input form-field named "__VIEWSTATE". Therefore, you can probably access the serialized ViewState using this:

Request.Form["__VIEWSTATE"]

But if you look at the source code of one of your pages (in your browser), you can see that the ViewState is just a (long) encoded string:

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

I'm not sure if logging that string will help you find any errors.

Upvotes: 0

Related Questions