Rick Strahl's Weblog  

Wind, waves, code and everything in between...
.NET • C# • Markdown • WPF • All Things Web
Contact   •   Articles   •   Products   •   Support   •   Advertise
Sponsored by:
West Wind WebSurge - Rest Client and Http Load Testing for Windows

Retrieve the full ASP.NET Form Buffer as a String


:P
On this page:

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.

Posted in ASP.NET  

The Voices of Reason


 

Nick Berardi
January 17, 2011

# re: Retrieve the full ASP.NET Form Buffer as a String

Hi Rick,

I have done something similar in my toolset. However something that I think you overlooked is the fact that ReadBinary only starts from the current position of the stream read. So if the stream has already been fully read you need to reset the position.

HttpRequest request = HttpContext.Current.Request;   
request.InputStream.Seek(0, SeekOrigin.Begin);
var reader = new StreamReader(request.InputStream);
return reader.ReadToEnd();


Does that make sense? It took me a while, and a lot of digging through Refector to figure out why if I requested this at the end of my handler that it wouldn't have any data in it.

Nick

Shiv Kumar
January 25, 2011

# re: Retrieve the full ASP.NET Form Buffer as a String

Hi Rick,

What you're really doing is extracting the Http Request Content and not the "Form buffer" as you call it here.

You should also note that if the request content is larger the 48K then this method won't work and you'll need to resort to using the multipart/form-data protocol (on the server side) in order to get at all of the content. Of course in that case you'll need to set the html form's enctype attribute to the same.

to be honest, I don't really get why you're doing this. Why not just log the Request.Form NameValueCollection?

Bob Pelton
January 25, 2011

# re: Retrieve the full ASP.NET Form Buffer as a String


Hey Great comment Rick !

Rick Strahl
January 26, 2011

# re: Retrieve the full ASP.NET Form Buffer as a String

@Shiv - usually I need to log the buffer when the data isn't form data, but something like XML or JSON.

Tracey
March 05, 2011

# re: Retrieve the full ASP.NET Form Buffer as a String

Rick... just thought I'd say thanks. You have actually helped me at least one other time, in my asp coding life, and I thought I'd just say thanks.

Unlike Shiv - i do get why you are doing it this way versus the form namevaluecollection. Like you, I needed to get the xml from the request body and I couldn't seem to find an example online until I found yours.

It is exactly what I needed.

I am using a special monitoring tool which shows request/response buffers. In this particular case, (for reasons specific to the monitoring tool, not worth getting into) it won't have the xml, when the request/response is captured a certain way by the tool. However, if I overwrite the response (which is blank in my case) with this request XML (using your guidance on formatting the request to string), then the monitoring tool has a way to take that xml from response and place it in the request the way i need.. so my goal is met.

Thanks

Thanks

Philip
March 11, 2011

# re: Retrieve the full ASP.NET Form Buffer as a String

Thanks Rick. Great tip. I was using SOAP serialize/deserialize but it took the 1KB of data and made it 22KB. I just wanted to see the raw data anyways and a namevaluecollection can be remade with a little parsing if needed.

Richard
March 30, 2011

# re: Retrieve the full ASP.NET Form Buffer as a String

You should probably use Request.ContentEncoding instead of Encoding.Default, in case the request is using a different encoding.

Also, if you just want to save the request to disk, you can use the SaveAs method [1], which has been around since .NET 1.1.

[1] http://msdn.microsoft.com/en-us/library/system.web.httprequest.saveas.aspx

Dhvanit Shah
June 08, 2018

# re: Retrieve the full ASP.NET Form Buffer as a String

Hi Rick,

Thanks for sharing this code snippet.

I am using this code in my HTTP Module. The purpose is to filter JSON text for some pre-defined text filters from all requests on my web application. If I found the filtered text/keyword then I simply stop request for further processing. But, the issue is when I don't find filtered text and request is good, then it results in error. It seems that FORMS authentication is failing. I tried to read cookie before content and re-added later on but still stuck there. Is there any restriction on reading this content like we can read it only once and then it does not work for second read?

I get 500 HTTP code with "There was an error processing the request." message which is very generic message.

Thanks.


West Wind  © Rick Strahl, West Wind Technologies, 2005 - 2024