'C# HttpClient PostAsJsonAsync adds a strange character to the body
i have an application in .NET 5, I'm trying to call an API with HttpClient using method PostAsJsonAsync, like this:
var jsonSerializerOptions = new JsonSerializerOptions
{
IgnoreNullValues = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = true,
};
var result = await client.PostAsJsonAsync("subjects", userRegistrationRequest, jsonSerializerOptions);
but I obtain always status code 500, so I tried to inspect the body request with fiddler and I noticed strange chars at the start and at the end of the body, like this:
5F
{
"id": "82240631-8c12-4b77-8626-7d36f93ceacc",
"language": "en",
"type": "subject"
}
0
But if I use classic PostAsync like this:
var result = await client.PostAsync("subjects", new StringContent(JsonSerializer.Serialize(userRegistrationRequest, jsonSerializerOptions),
Encoding.UTF8, MediaTypeNames.Application.Json));
the body is correct:
{
"id": "82837dba-c86d-4cf2-9c98-7f402b2761a1",
"language": "en",
"type": "subject"
}
and it works fine. Why does this happen? Thank you.
Solution 1:[1]
As Stephen pointed out in the comment, PostAsJsonAsync uses JsonContent. JsonContent uses Transfer-Encoding: chunked (instead of setting Content-Length; See MDN docs), so it can stream the data.
The 5F in your request is hex for 95, specifying that the upcoming chunk of the content is 95 characters long. The 0 indicates that the upcoming (zero-length) chunk is the terminating chunk, and thus the end of the content.
This is all totally valid HTTP/1.1. It's likely that whatever server is responding with 500 is just not correctly implementing HTTP.
As you pointed out, a workaround is to create your own StringContent, which won't use chunked transfer encoding, and will instead set the Content-Length header, which is more likely to be accepted by weak HTTP implementations ?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
