How to get HttpRequestMessage data

C#asp.net Mvc

C# Problem Overview


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;
}

C# Solutions


Solution 1 - C#

From this answer:

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

Note: As seen in the comments, this code could cause a deadlock and should not be used. See this blog post for more detail.

Solution 2 - C#

using System.IO;

string requestFromPost;
using( StreamReader reader = new StreamReader(HttpContext.Current.Request.InputStream) )
{
    reader.BaseStream.Position = 0;
    requestFromPost = reader.ReadToEnd();
}

Solution 3 - C#

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.

Solution 4 - C#

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1615362View Question on Stackoverflow
Solution 1 - C#MansfieldView Answer on Stackoverflow
Solution 2 - C#Zebing LinView Answer on Stackoverflow
Solution 3 - C#Khanh TOView Answer on Stackoverflow
Solution 4 - C#codeMonkeyView Answer on Stackoverflow