Receive PostAsync in FromBody as parameter
I am trying to read a JSON string from a web API controller that is sent via a method HttpClient.PostAsync()
. But for some reason, RequestBody
always null
.
My request looks like this:
public string SendRequest(string requestUrl, StringContent content, HttpMethod httpMethod)
{
var client = new HttpClient { BaseAddress = new Uri(ServerUrl) };
var uri = new Uri(ServerUrl + requestUrl); // http://localhost/api/test
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response;
response = client.PostAsync(uri, content).Result;
if (!response.IsSuccessStatusCode)
{
throw new ApplicationException(response.ToString());
}
string stringResult = response.Content.ReadAsStringAsync().Result;
return stringResult;
}
I am calling this method like this
var content = new StringContent(JsonConvert.SerializeObject(testObj), Encoding.UTF8, "application/json");
string result = Request.SendRequest("/api/test", content, HttpMethod.Post);
Now my Web API method is currently reading the submit data like this:
[HttpPost]
public string PostContract()
{
string httpContent = Request.Content.ReadAsStringAsync().Result;
return httpContent;
}
This works great. The property stringResult
contains the string returned by the controller method. But I would like my controller method to be as follows:
[HttpPost]
public string PostContract([FromBody] string httpContent)
{
return httpContent;
}
The request seems to work when received 200 - OK
, but stringResult
from the method SendRequest
always null
.
Why isn't the method in which I use the RequestBody
as parameter being used ?
source to share
Since you are posting as application/json
, the framework is trying to deserialize it rather than providing a raw string. Regardless of the type testObj
in your example, use this type for the controller action parameter and return type instead string
:
[HttpPost]
public MyTestType PostContract([FromBody] MyTestType testObj)
{
return testObj;
}
source to share