Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net core 1.0 mvc. Get raw content from Request.Body

I am trying to get the raw content of Request.Body in asp.net core 1.0 and I was wondering what the proper way of getting the entire body as a byte[] is. If you have any experience with similar situation and know the “proper” way of doing it, please share.

like image 900
Isak Ågren Avatar asked Feb 27 '16 21:02

Isak Ågren


2 Answers

Request.Body is a Stream. The stream has the Read method that takes a buffer which is a byte array you can read the data into. Since you may not know the size of the stream and even not all the content can be available you need to do this in the loop until you read all the data from the stream - this stackoverflow answer shows how to do that (if you don't want to block your thread could use ReadAsync). Alternatively - if you would like to read content to a String you could use the StreamReader class.

like image 146
Pawel Avatar answered Sep 30 '22 14:09

Pawel


I used this code...

using (var requestBodyStream = new MemoryStream())
{
    var body = request.Body;
    await request.Body.CopyToAsync(requestBodyStream);
    requestBodyStream.Seek(0, SeekOrigin.Begin);
    requestPayload.Body = await new StreamReader(requestBodyStream).ReadToEndAsync();
}
like image 29
Remotec Avatar answered Sep 30 '22 15:09

Remotec