asp.net-mvc - 当指定 UTF-8 时,为什么 ASP.NET MVC 中的 ContentResult Controller 返回 UTF-16?

标签 asp.net-mvc utf-8 utf-16 actionresult

我有一个为嵌入式设备返回 XML 的 ActionResult。相关代码为:

return Content(someString, "text/xml", Encoding.UTF8);

即使指定了 UTF-8,生成的 XML 仍为:

<?xml version="1.0" encoding="utf-16"?>

ASP.NET MVC 被编译为 AnyCPU,并在 Windows 2008 服务器上运行。

为什么它不返回 UTF-8 编码的 XML?

最佳答案

您混淆了 HTTP 响应的编码和响应中包含的 XML 的编码。当您序列化 XML 时,您需要指定它需要采用 UTF-8 编码。在 ContentResult 上设置编码只是告知另一端的浏览器响应的编码方式,它不会将 XML 从一种编码转换为另一种编码。如果您查看 ContentResult 的代码,您会发现它只是在使用您指定的编码和内容类型设置响应 header 之后执行 Response.Write( Content )。

关于asp.net-mvc - 当指定 UTF-8 时,为什么 ASP.NET MVC 中的 ContentResult Controller 返回 UTF-16?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1561891/

相关文章:

c# - Asp.Net Core 中的@Html.Action

c# - 向asp.net webapi传入长参数

C#回调接收UTF8字符串

php - 通过 PHP 解码数字 html 实体

python - 从十六进制字符串转换为 unicode

带有 utf-16 代理项对的 javascript 和字符串操作

python - 字节类型的 UnicodeDecodeError

utf-8 - utf8_general_ci 或 utf8mb4 或...?

asp.net mvc路由id参数

c# - 使用 .Net HttpClient 访问 cloudant 数据库