C# HttpClient无法分析“UTF-8”内容类型

C# HttpClient无法分析“UTF-8”内容类型,c#,httpclient,C#,Httpclient,我在中遇到一个已知的错误。只要服务器响应包含UTF-8(包括引号),就会触发异常: The character set provided in ContentType is invalid. Cannot read content as string using an invalid character set. ---> System.ArgumentException: '"utf-8"' is not a supported encoding name. 示例代码: HttpCl

我在中遇到一个已知的错误。只要服务器响应包含UTF-8(包括引号),就会触发异常:

The character set provided in ContentType is invalid. Cannot read content as string using an invalid character set. ---> System.ArgumentException: '"utf-8"' is not a supported encoding name. 
示例代码:

HttpClient _client = new HttpClient();
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, "https://www.facebook.com");
requestMessage.Headers.Add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.4044.55 Safari/537.36");

HttpResponseMessage response = _client.SendAsync(requestMessage).GetAwaiter().GetResult();

通常的解决办法是什么?我正在使用.NETFramework 4.6.1.

解决引用的问题:

using (var client = new HttpClient())
{
    HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, 
        "https://www.facebook.com");
    HttpResponseMessage response = await client.SendAsync(requestMessage);

    byte[] buf = await response.Content.ReadAsByteArrayAsync();
    string content = Encoding.UTF8.GetString(buf);
}

要解决引用的问题,请执行以下操作:

using (var client = new HttpClient())
{
    HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, 
        "https://www.facebook.com");
    HttpResponseMessage response = await client.SendAsync(requestMessage);

    byte[] buf = await response.Content.ReadAsByteArrayAsync();
    string content = Encoding.UTF8.GetString(buf);
}

我无法重现使用.net 4.8的HttpClient的问题,可能是您应该升级。显然,如果没有设置用户代理,facebook会返回不同的内容类型。尝试使用用户代理。。请参阅我的测试中更新的代码,它在引号中返回utf-8。我已经设置了useragent。但它起了作用。OP没有提到的是:您必须调用response.Content.ReadAsStringAsync来查看utf-8引起的异常。在这种情况下,您可以通过使用Encoding.UTF8.GetString和ReadAsByteArrayAsync的组合来解决此问题。@weichch:实际上,我的代码没有使用“ReadAsTringAsync”,这可能是它无法为meI工作的原因。HttpClient使用.net 4.8时出现问题,很明显,如果没有设置用户代理,facebook会返回不同的内容类型。尝试使用用户代理。。请参阅我的测试中更新的代码,它在引号中返回utf-8。我已经设置了useragent。但它起了作用。OP没有提到的是:您必须调用response.Content.ReadAsStringAsync来查看utf-8引起的异常。在这种情况下,您可以通过使用Encoding.UTF8.GetString和ReadAsByteArrayAsync的组合来解决这个问题。@weichch:实际上我的代码没有使用“ReadAsTringAsync”,这可能是它对我有效的原因