1

I'm trying to post JSON data to web api, both projects run on my local machine.

using (var client = new HttpClient())
{
    client.BaseAddress = new Uri(@"http://localhost:53818/");
    var result = client.PostAsync("api/values", new StringContent(data, Encoding.UTF8, "application/json")).Result;
    string resultContent = result.Content.ReadAsStringAsync().Result;
    Console.WriteLine(resultContent);
}

Received values in This post method is NULL

public HttpResponseMessage Post([FromBody]string value)
{
    return new HttpResponseMessage(HttpStatusCode.Created);
}

EDIT ----------- So I managed to figure out what the issue was. I've substituted this line of code

client.PostAsync("api/values", new StringContent(data, Encoding.UTF8, "application/json")).Result;

with the following and it worked, if someone will post the explanation I will be grateful

var response = client.PostAsJsonAsync("api/values", data).Result;
mr. Holiday
  • 1,780
  • 2
  • 19
  • 37

2 Answers2

1

This is becouse WebApi isn't good at serializing primitive types from the body, when you are sending the 'Content-Type' Header as application/json the framework is trying to serialize the content with the set Json serializer and isn't able, that's why you are getting null in the variable.

You can either

  1. Change the type of the parameter from string to JToken or
  2. Include a Media Type Formatter that handles plain text (see https://stackoverflow.com/a/29914360/1422608)
Community
  • 1
  • 1
evilpilaf
  • 1,991
  • 2
  • 21
  • 38
0

Because you call values and your method expect value. Change your call to value or change the method signature for values which in this case would make more sense

Marc Roussel
  • 459
  • 9
  • 20