How to get raw request body in ASP.NET

asp.nethttp

In the HttpApplication.BeginRequest event, how can I read the entire raw request body? When I try to read it the InputStream is of 0 length, leading me to believe it was probably already read by ASP.NET.

I've tried to read the InputStream like this:

using (StreamReader reader = new StreamReader(context.Request.InputStream))
{
    string text = reader.ReadToEnd();
}

But all I get is an empty string. I've reset the position back to 0, but of course once the stream is read it's gone for good, so that didn't work. And finally, checking the length of the stream returns 0.

Edit: This is for POST requests.

Best Answer

The request object is not populated in the BeginRequest event. You need to access this object later in the event life cycle, for example Init, Load, or PreRender. Also, you might want to copy the input stream to a memory stream, so you can use seek:

protected void Page_Load(object sender, EventArgs e)
{
    MemoryStream memstream = new MemoryStream();
    Request.InputStream.CopyTo(memstream);
    memstream.Position = 0;
    using (StreamReader reader = new StreamReader(memstream))
    {
        string text = reader.ReadToEnd();
    }
}