I am using HttpClient to send a post request to a remote server where I do not have control and trying to get the response as following
HttpResponseArgs result = //Make the request with HttpClient object ( I am skipping it here)
var stringResult = result?.Content.ReadAsStringAsync().Result; // exception thrown here as "UTF-8" is not supported encoding name
on debug I found the Content-Type header in response from remote server is set as "text/xml; charset ="UTF-8"" Please note the extra "" between UTF-8 this is causing the error if I remove the header from response and put a new content-Type header with "text/xml; charset =UTF-8". please note I removed the extra Quote around UTF-8 the code
result?.Content.ReadAsStringAsync().Result; // works fine now
Please suggest what can I do? I feel its a bug in .net framework as postman can interpret response of remote server in correct way.
the problem is in double quoate around UTF-8 in header of response
You can use custom EncodingProvider
public class Utf8EncodingProvider : EncodingProvider
{
public override Encoding GetEncoding(string name)
{
return name == "\"UTF-8\"" ? Encoding.UTF8 : null;
}
public override Encoding GetEncoding(int codepage)
{
return null;
}
public static void Register()
{
Encoding.RegisterProvider(new Utf8EncodingProvider());
}
}
Usage based on your question code:
Utf8EncodingProvider.Register(); //You should call it once at startup of your application
HttpResponseArgs result = //Make the request with HttpClient object ( I am skipping it here)
var stringResult = result?.Content.ReadAsStringAsync().Result; // Must be executed without exception.