I'm trying to capture the raw request data for accountability and want to pull the request body content out of the Request object.
I've seen suggestions doing a Request.InputStream, but this method is not available on the Request object.
Any idea of how to get a string representation of the Request.Content body?
You can get the raw data by calling
ReadAsStringAsAsync
on theRequest.Content
property.There are various overloads if you want it in a byte or in a stream. Since these are async-methods you need to make sure your controller is async:
EDIT: if you're receiving an empty string from this method, it means something else has already read it. When it does that, it leaves the pointer at the end. An alternative method of doing this is as follows:
In this case, your endpoint doesn't need to be async (unless you have other async-methods)
In your comment on @Kenneth's answer you're saying that
ReadAsStringAsync()
is returning empty string.That's because you (or something - like model binder) already read the content, so position of internal stream in Request.Content is on the end.
What you can do is this:
For other future users who do not want to make their controllers asynchronous, or cannot access the HttpContext, or are using dotnet core (this answer is the first I found on Google trying to do this), the following worked for me: