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?
In this case you get a the original string back as a JSON response – JSON because the default format for Web API is JSON.
Use [FromUri] attribute to force Web API to get the value of complex type from the query string and [FromBody] attribute to get the value of primitive type from the request body, opposite to the default rules.
When you need to send data from a client (let's say, a browser) to your API, you send it as a 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.
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:
public static string GetRequestBody() { var bodyStream = new StreamReader(HttpContext.Current.Request.InputStream); bodyStream.BaseStream.Seek(0, SeekOrigin.Begin); var bodyText = bodyStream.ReadToEnd(); return bodyText; }
You can get the raw data by calling ReadAsStringAsAsync
on the Request.Content
property.
string result = await Request.Content.ReadAsStringAsync();
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:
public async Task<IHttpActionResult> GetSomething() { var rawMessage = await Request.Content.ReadAsStringAsync(); // ... return Ok(); }
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:
public IHttpActionResult GetSomething() { var reader = new StreamReader(Request.Body); reader.BaseStream.Seek(0, SeekOrigin.Begin); var rawMessage = reader.ReadToEnd(); return Ok(); }
In this case, your endpoint doesn't need to be async (unless you have other async-methods)
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