Bread
Bread

Reputation: 443

Post string request

I have this Post request handler in an asp.net core webapi

[HttpPost()]
public IActionResult Post([FromBody]string value)
{
    if (value == null)
    {
        return new HttpStatusCodeResult(400);
    }
    else
    {
        return new HttpStatusCodeResult(200);
    }
}

I am trying post a string to it using HttpClient from another app

using(var client = new HttpClient())
{
    var content = new StringContent("test test");
    var response = client.PostAsync("http://localhost:57316/api/values", content).Result;
    var responseString = response.Content.ReadAsStringAsync().Result;
    Console.WriteLine(responseString);
}

the request gets received when I debug the handler above, but value is always null, I expect it to be "test test",waht am I doing wrong?

Upvotes: 2

Views: 940

Answers (1)

Dai
Dai

Reputation: 155608

As you're not setting an explicit Content-Type on the request, it's possible ASP.NET Web API is interpreting it as JSON, but as "test test" (by itself, without quotes) is not valid JSON it will fail.

Try one of these:

  1. Set the request's Content-Type header to "text/plain".
  2. Try sending the value as a valid JavaScript string with double-quotes (i.e. send new StringContent("\"test test\"");
  3. As JSON readers generally don't like single values, you could set the Request type as some POCO and set the string that way.

Upvotes: 1

Related Questions