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.
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.
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();
}
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