I'm trying to call an API with PostAsJsonAsync, but it doesn't work as I would expect.
Repo:
- Create an ASP.NET WebAPi project (.NET Framework 4.7.2)
Replace the
Postmethod inValuesControllerto// POST api/values public async Task<IHttpActionResult> Post(string[] array) { var suffix = array == null ? "is null" : $"has {array.Length} elements"; var message = $"`array` {suffix}"; return Ok(message); }Create a console app to hit the API.
static async Task Main(string[] args) { const string url = "http://localhost:6757/api/values"; var value = new List<string> { "a", "b" }; var client = new HttpClient(); var response = await client.PostAsJsonAsync(url, value); var message = await response.Content.ReadAsStringAsync(); Console.WriteLine(message); // Do what I think PostAsJsonAsync is essentially doing var json = JsonConvert.SerializeObject(value); var content = new StringContent(json, Encoding.UTF8, "application/json"); response = await client.PostAsync(url, content); message = await response.Content.ReadAsStringAsync(); Console.WriteLine(message); }Run the WebApi followed by the console app
EXPECTED OUTPUT:
"
arrayhas 2 elements""
arrayhas 2 elements"
ACTUAL OUTPUT:
"
arrayis null""
arrayhas 2 elements"
So I changed the Post method to compare content strings at the request.
public async Task<IHttpActionResult> Post()
{
var value = await Request.Content.ReadAsStringAsync();
return Ok();
}
They both set value to ["a","b"].
So why is PostAsJsonAsync not working like I think it should?