Retrieve the full ASP.NET Form Buffer as a String

Posted by Rick Strahl on West-Wind See other posts from West-Wind or by Rick Strahl
Published on Mon, 17 Jan 2011 11:04:59 GMT Indexed on 2011/01/17 11:54 UTC
Read the original article Hit count: 356

Filed under:

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. You probably don’t want to call this if you have a massive inbound form buffer, or if the data you’re retrieving is binary. It’s probably a good idea to check the inbound content type before calling this function with something like this:

var formBuffer = string.Empty;

if (Request.ContentType.StartsWith("text/") || 
    Request.ContentType == "application/x-www-form-urlencoded") )
{
    formBuffer = FormBufferToString();
}

to ensure you’re working only on content types you can actually view as text.

Now if I can only remember the name of this function in my library – it’s part of the static WebUtils class in the West Wind Web Toolkit if you want to check out a number of other useful Web helper functions.

© Rick Strahl, West Wind Technologies, 2005-2011
Posted in ASP.NET  
kick it on DotNetKicks.com

© West-Wind or respective owner

Related posts about ASP.NET