How to read a POST’s raw data
April 13, 2011 by: B.HardingI was tasked with accepting data posted from an AS400 to a web page. The only problem is that for some reason the Request.Form was empty. I’m not sure if this violates the RFC or not but I have to deal with it. Luckily I can adapt with a few short lines.
It turns out that this is caused by not using the correct content-type when the request was made. The request.form isn’t parsed unless the content-type is application/x-www-form-urlencoded.
The way to read the raw data is to read the Request’s InputStream.
Here are the steps.
Create a stream and set it to the Reqest.InputStream
Read it into a byte array
Encode the Byte array to a string.
string sPostData = String.Empty;
if (Request.RequestType=="POST")
{
System.IO.Stream myStream = Request.InputStream;
// Read the file into the byte array.
byte[] input = new byte[Request.InputStream.Length];
myStream.Read(input, 0, (int)Request.InputStream.Length - 1);
//encode to a string
System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
sPostData = enc.GetString(input);
}
if (sPostData!=string.Empty) {
//parse and process away
}


