Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the raw request body from the Request.Content object using .net 4 api endpoint

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?

Watch variable

like image 850
Mark Kadlec Avatar asked Feb 23 '16 22:02

Mark Kadlec


People also ask

Which is the default formatter for the incoming request 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.

How do I pass body parameters in Web API?

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.

What is request body in API?

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.


2 Answers

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; } 
like image 65
Gh61 Avatar answered Sep 24 '22 00:09

Gh61


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)

like image 20
Kenneth Avatar answered Sep 20 '22 00:09

Kenneth