API Get requires Content-Type application/json;charset=UTF-8 - Issue with Http Client
Solution 1
Try to set the property:
new MediaTypeHeaderValue("application/json")
{
CharSet = Encoding.UTF8.WebName
};
Solution 2
Try this one
HttpClient httpClient= new HttpClient();
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json; charset=utf-8");
Lee Ames
Updated on July 19, 2022Comments
-
Lee Ames almost 2 years
I am working with an API service that requires Content-Type to be set to application/json;charset=UTF-8.
If I make a request without the charset=UTF-8 I get a 406 - Not Acceptable.
I can make a call through Postman setting the Content-Type as required, but if I use my .Net Http Client I get the error:
System.FormatException: 'The format of value 'application/json;charset=UTF-8' is invalid.'
Is there anyway I can work around this validation and force the Http Client to accept the value?
UPDATE:
Here is my latest attempt,it still throws the error.
Body.Headers.ContentType = new MediaTypeHeaderValue("application/json;charset=UTF-8");
UPDATE: Content-Type is indeed an invalid header. The API Developers removed it at our request.
-
Lee Ames over 5 yearsI did try this one, it returns false, indicating that it did not add the header. Also when I examine the client object I can see that it was not added to the list of headers. But thanks for the suggestion.
-
Roman Marusyk over 5 yearsThe OP says that "a request without the charset=UTF-8 I get a 406 - Not Acceptable."
-
Lee Ames over 5 yearsI got the same validation error as before. But I do appreciate the suggestion!
-
Roman Marusyk almost 4 years@Neo yes, for me, in old asp.net (not Core). what problem do you have with it?
-
Epicycle almost 2 yearsProbably better do a client.DefaultRequestHeaders.Accept.Clear() before but other than that this should be the accepted answer. Edit: Nevermind op is talking about the content-type not the accept header.