c# - 为什么这个 UTF-16 HTTP 响应在生成的流中最终变成 UTF-8?

标签 c# encoding http-headers content-type asp.net-core-3.1

我遇到一个问题,服务向我返回 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?! 
       }
   }
} 

所以最初响应看起来很好,但是一旦到达streamReader,它似乎就恢复为utf-8。为什么?

最佳答案

您可以在构造函数中指定 StreamReader 应使用的编码。 在你的情况下,它应该看起来像这样:

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

关于c# - 为什么这个 UTF-16 HTTP 响应在生成的流中最终变成 UTF-8?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63052689/

相关文章:

javascript - 如何取消修补 Javascript 对象中的方法?具体来说是 XMLHttpRequest.open

c# - WPF MVVM : Call method from control from inside attached usercontrol

c# - 列出 DataTable 值

VB6 的 Base64 编码的 C# 版本

python收集ascii和utf-8的东西

http-headers - 冒号和等号在 http header 中的处理方式相同吗?

c# - 将带有封装 int 的字符串解析为包含其他要忽略的数字的数组

c# - Linq递归父子

php - strftime 日期格式中的德语变音符号 - 正确的 utf-8 编码?

asp.net - 强制单个背景图像*不*缓存