Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get HttpRequestMessage data

Tags:

c#

asp.net-mvc

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;
}
like image 714
user1615362 Avatar asked Jul 31 '13 13:07

user1615362


3 Answers

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.

like image 123
Mansfield Avatar answered Sep 24 '22 12:09

Mansfield


using System.IO;

string requestFromPost;
using( StreamReader reader = new StreamReader(HttpContext.Current.Request.InputStream) )
{
    reader.BaseStream.Position = 0;
    requestFromPost = reader.ReadToEnd();
}
like image 42
Zebing Lin Avatar answered Sep 22 '22 12:09

Zebing Lin


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.

like image 21
Khanh TO Avatar answered Sep 25 '22 12:09

Khanh TO