For those who troubled with charset
I had very special case that the service provider didn't accept charset, and they refuse to change the substructure to allow it... Unfortunately HttpClient was setting the header automatically through StringContent, and no matter if you pass null or Encoding.UTF8, it will always set the charset...
Today i was on the edge to change the sub-system; moving from HttpClient to anything else, that something came to my mind..., why not use reflection to empty out the "charset"? ... And before i even try it, i thought of a way, "maybe I can change it after initialization", and that worked.
Here's how you can set the exact "application/json" header without "; charset=utf-8".
var jsonRequest = JsonSerializeObject(req, options); // Custom function that parse object to string var stringContent = new StringContent(jsonRequest, Encoding.UTF8, "application/json"); stringContent.Headers.ContentType.CharSet = null; return stringContent;
Note: The null value in following won't work, and append "; charset=utf-8"
return new StringContent(jsonRequest, null, "application/json");
EDIT
@DesertFoxAZ suggests that also the following code can be used and works fine. (didn't test it myself, if it work's rate and credit him in comments)
stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
EDIT 2
.NET 8 (Or maybe all .NET or even .NET Core version)
As @EionRobb explained, the new .NET does not behave same as the old one, setting the stringContent.Headers.ContentType to null is the answer, and this new MediaTypeHeaderValue("application/json") may not work. Just Updated, Not tested by myself.