为什么这个 UTF-16 HTTP 响应在生成的流中以 UTF-8 结尾?

Why does this UTF-16 HTTP response end up as UTF-8 when in the resulting Stream?

我遇到一个问题,服务向我返回 HTTP Header:

Content-Type: application/json; charset=utf-16

当它被 C# 序列化时,它以 UTF-8 流结束,这显然会中断。 utf-16 似乎是 IANA spec 中的有效编码。那么为什么这段代码不起作用?

System.Net.Http.HttpClient httpClient ...;
using (var response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead))
{
   //response.Content.Headers.ContentType.CharSet = "utf-16"
   using (var responseContentStream = await response.Content.ReadAsStreamAsync())
   {
       using (var streamReader = new StreamReader(stream))
       {
          //streamReader.CurrentEncoding.BodyName returns utf-8 here?! 
       }
   }
} 

所以最初 response 看起来不错,但是一旦达到 streamReader 它似乎又恢复为 utf-8。为什么?

您可以在构造函数中指定 StreamReader 应使用的编码。 在您的情况下,它应该如下所示:

using (var streamReader = new StreamReader(stream, Encoding.Unicode, true))
{
  // The reader should read the Stream with UTF-16 here
}