I have created a HttpModule to capture requests for auditing purposes.
For Ajax requests to a web method I would like to also log the JSON data associated with the request.
E.g Request
POST /MyPage.aspx/AddRecord HTTP/1.1
x-requested-with: XMLHttpRequest
Accept-Language: en-gb
Referer: http://fiddlerlocal:5000/AddRecord.aspx
Accept: application/json, text/javascript, /
Content-Type: application/json; charset=utf-8
UA-CPU: x86
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)
Host: fiddlerlocal:5000
Content-Length: 287
Connection: Keep-Alive
Pragma: no-cache
Cookie: .....
{"id":"282aa3b5-b55f-431c-916e-60433fdb61c0","date":"8-6-2010"}
I have tried a variety of methods to read the JSON ({"id":"282aa3b5-b55f-431c-916e-60433fdb61c0","date":"8-6-2010"}) from the HttpContext.InputStream.
Example 1:
StreamReader reader = new StreamReader(request.InputStream);
string encodedString = reader.ReadToEnd(); -- ReadToEnd returns an empty string
Example 2:
using (MemoryStream ms = new MemoryStream())
{
byte[] buffer = new byte[request.ContentLength];
request.InputStream.Read(buffer, 0, request.ContentLength);
ms.Write(buffer, 0, request.ContentLength); -- The byte array contains the correct number of bytes but each byte has a value of 0 - encoded some how?
return Convert.ToBase64String(ms.ToArray()); -- doesn't do anything
return Encoding.UTF8.GetString(ms.ToArray()); -- doesn't do anything
}
How can I successfully extract the data from HttpContext.InputStream?
Thanks in advance.
I needed to reset the position of the stream before reading...
request.InputStream.Position = 0;
using (StreamReader inputStream = new StreamReader(request.InputStream))
{
return inputStream.ReadToEnd();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With