[c#] How to get HttpRequestMessage data

I have an MVC API controller with the following action.

I don't understand how to read the actual data/body of the Message?

[HttpPost]
public void Confirmation(HttpRequestMessage request)
{
    var content = request.Content;
}

This question is related to c# asp.net-mvc

The answer is


In case you want to cast to a class and not just a string:

YourClass model = await request.Content.ReadAsAsync<YourClass>();

I suggest that you should not do it like this. Action methods should be designed to be easily unit-tested. In this case, you should not access data directly from the request, because if you do it like this, when you want to unit test this code you have to construct a HttpRequestMessage.

You should do it like this to let MVC do all the model binding for you:

[HttpPost]
public void Confirmation(YOURDTO yourobj)//assume that you define YOURDTO elsewhere
{
        //your logic to process input parameters.

}

In case you do want to access the request. You just access the Request property of the controller (not through parameters). Like this:

[HttpPost]
public void Confirmation()
{
    var content = Request.Content.ReadAsStringAsync().Result;
}

In MVC, the Request property is actually a wrapper around .NET HttpRequest and inherit from a base class. When you need to unit test, you could also mock this object.


  System.IO.StreamReader reader = new System.IO.StreamReader(HttpContext.Current.Request.InputStream);
  reader.BaseStream.Position = 0;
  string requestFromPost = reader.ReadToEnd();