Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the raw Request in ASP.NET MVC

Tags:

I need to get the raw request string. Below is an example of the http request sent to the Controller. Actually, I need Post data (last line). How can I get that?

Notice that I don't want to use the automatic JSON model binder. Actually, I need the raw JSON text

POST http://www.anUrl.com/CustomExport/Unscheduled HTTP/1.1
Accept: application/json, text/javascript, */*; q=0.01
Content-Type: application/json; charset=utf-8
X-Requested-With: XMLHttpRequest
Referer: http://www.anUrl.com/CustomExport
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)
Host: localhost:8000
Content-Length: 102
Connection: Keep-Alive
Pragma: no-cache

{"runId":"1","fileDate":"8/20/2012","orderStartMinDate":"10/02/2012","orderStartMaxDate":"10/02/2012"}

This last line is what I need. This doesn't come in

var input = new StreamReader(Request.InputStream).ReadToEnd();
like image 538
Pato Loco Avatar asked Oct 02 '12 18:10

Pato Loco


2 Answers

At that point the stream has already been read to the end. You need to set the position of the InputStream back to the beginning before you can read it yourself.

Request.InputStream.Position = 0;
var input = new StreamReader(Request.InputStream).ReadToEnd();
like image 194
Louis Ricci Avatar answered Sep 27 '22 22:09

Louis Ricci


@louis-ricci answear is correct, but bear in mind that if you use [FromBody] in your Action Method, you'll get exception when calling Request.InputStream, since [FromBody] already reads the request body in order to serialize to the model by invoking HttpRequest.GetBufferlessInputStream(), and this method can't be invoked twice. To get around this, simply don't use [FromBody] in your request and serialize the raw request string manually to your model.

Edit: For better context and search results on this topic, the error thrown has this message:

This method or property is not supported after HttpRequest.GetBufferlessInputStream has been invoked
like image 40
Edgar Froes Avatar answered Sep 28 '22 00:09

Edgar Froes