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;
}
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.
using System.IO;
string requestFromPost;
using( StreamReader reader = new StreamReader(HttpContext.Current.Request.InputStream) )
{
reader.BaseStream.Position = 0;
requestFromPost = reader.ReadToEnd();
}
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.
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