当指定 UTF-8 时,为什么 ASP.NET MVC 中的 ContentResult 控制器返回 UTF-16?

发布于 2024-08-07 20:14:46 字数 316 浏览 2 评论 0原文

我有一个为嵌入式设备返回 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?

I have an ActionResult that returns XML for an embedded device. The relevant code is:

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

Even though UTF-8 is specified, the resulting XML is:

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

The ASP.NET MVC is compiled as AnyCPU and runs on a Windows 2008 server.

Why is it not returning UTF-8 encoded XML?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

娇女薄笑 2024-08-14 20:14:46

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

You are confusing the encoding of the HTTP response with the encoding of the XML contained in the response. When you serialize the XML you need to specify that it needs to be UTF-8 encoded. Setting the encoding on the ContentResult simply informs the browser on the other end how the response was encoded, it doesn't transform the XML from one encoding to another. If you look at the code for ContentResult, you'll see that it it simply does a Response.Write( Content ) -- after setting the Response headers with the encoding and content types you specify.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文