You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在ASP.NET Core中如何POST UTF-16编码的XML请求体

问题原因

.NET Core 自带的 XML 序列化输入格式化器默认仅支持 UTF-8 编码,收到 UTF-16 编码的请求体时会默认按 UTF-8 规则解码,解码结果与 XML 声明中指定的 UTF-16 编码不匹配,因此抛出 XmlException 异常。你当前的配置仅自定义了 XML 输出格式化器的规则,没有对输入格式化器的支持编码做扩展。

修复步骤

修改 Startup.cs 中 ConfigureServices 方法的 MVC 配置,显式为 XML 输入格式化器添加 UTF-16 编码支持即可,完整配置如下:

using Microsoft.AspNetCore.Mvc.Formatters;
using System.Text;

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddDbContext<CFContext>();

    services.AddMvc(options => {
        // 保留你原有XML输出格式化器配置
        XmlWriterSettings outputSettings = new XmlWriterSettings
        {
            OmitXmlDeclaration = false
        };
        var xmlOutputFormatter = new XmlSerializerOutputFormatter(outputSettings);
        // 若需要服务端也支持返回UTF-16编码的响应,可添加以下两行
        // xmlOutputFormatter.SupportedEncodings.Add(Encoding.Unicode);
        // xmlOutputFormatter.SupportedEncodings.Add(Encoding.BigEndianUnicode);
        options.OutputFormatters.Add(xmlOutputFormatter);

        // 新增XML输入格式化器配置,添加UTF-16编码支持
        var xmlInputFormatter = new XmlSerializerInputFormatter(options);
        // 保留原有UTF-8支持
        xmlInputFormatter.SupportedEncodings.Add(Encoding.UTF8);
        // 添加UTF-16小端序支持(绝大多数场景下的UTF-16都是该编码)
        xmlInputFormatter.SupportedEncodings.Add(Encoding.Unicode);
        // 若需要支持UTF-16大端序,取消注释下一行
        // xmlInputFormatter.SupportedEncodings.Add(Encoding.BigEndianUnicode);
        options.InputFormatters.Add(xmlInputFormatter);
    }).AddXmlSerializerFormatters();
}
注意事项
  • 若客户端发送请求时会在 Content-Type 请求头中指定 charset=utf-16,无需额外配置即可匹配处理
  • 若客户端未在请求头指定 charset,格式化器会自动读取 XML 声明中的 encoding 属性匹配对应编码,只要 SupportedEncodings 列表中存在对应编码即可正常解析

内容的提问来源于stack exchange,提问作者Marlon Daniel Zaldivar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 14:27:03