Tuesday, January 18, 2011

Retrieve the full ASP.NET Form Buffer as a String

Did it again today: For logging purposes I needed to capture the full Request.Form data as a string and while it’s pretty easy to retrieve the buffer it always takes me a few minutes to remember how to do it. So I finally wrote a small helper function to accomplish this since this comes up rather frequently especially in debugging scenarios or in the immediate window.
Here’s the quick function to get the form buffer as string:

/// <summary>
/// Returns the content of the POST buffer as string
/// </summary>
/// <returns></returns>
public static string FormBufferToString()
{
   HttpRequest Request = HttpContext.Current.Request;          
   if (Request.TotalBytes > 0)          
       return Encoding.Default.GetString(Request.BinaryRead(Request.TotalBytes));
   return string.Empty;
}

Clearly a simple task, but handy to have in your library for reuse.

Read more: Rick Strahl's blog