Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get raw request body in ASP.NET?

Tags:

http

asp.net

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.

like image 859
Josh M. Avatar asked Jun 15 '11 18:06

Josh M.


People also ask

What is EnableBuffering?

EnableBuffering(HttpRequest) Ensure the request Body can be read multiple times. Normally buffers request bodies in memory; writes requests larger than 30K bytes to disk. EnableBuffering(HttpRequest, Int32) Ensure the request Body can be read multiple times.

Which is the default formatter for the incoming request body?

In this case you get a the original string back as a JSON response – JSON because the default format for Web API is JSON.

What is the request body?

A request body is data sent by the client to your API. A response body is the data your API sends to the client. Your API almost always has to send a response body. But clients don't necessarily need to send request bodies all the time.


2 Answers

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();     } } 
like image 97
Pål Thingbø Avatar answered Sep 29 '22 15:09

Pål Thingbø


Pål's answer is correct, but it can be done much shorter as well:

string req_txt; using (StreamReader reader = new StreamReader(HttpContext.Current.Request.InputStream)) {     req_txt = reader.ReadToEnd(); } 

This is with .NET 4.6.

like image 21
Ian Avatar answered Sep 29 '22 17:09

Ian