.NET 6 API被Excel QueryTable调用时丹麦语字符编码异常问题
解决ASP.NET Core 6 Web API Excel QueryTable丹麦语字符乱码问题
问题根源在于Excel QueryTable读取纯文本响应时,默认使用系统ANSI编码(如Windows-1252),而ASP.NET Core默认以UTF-8输出文本,编码不匹配导致乱码。旧.NET 4应用默认使用ANSI编码输出,因此显示正常。
单个控制器方法解决方案
直接在目标接口中指定输出编码为Windows-1252,并使用该编码转换字符串后写入响应:
[HttpGet] [Route("problem")] public async Task Problem() { // 获取Windows-1252编码(西欧ANSI编码,兼容丹麦语字符) var targetEncoding = Encoding.GetEncoding(1252); // 设置响应ContentType并指定编码 Response.ContentType = $"text/plain; charset={targetEncoding.WebName}"; await Response.StartAsync(); // 将字符串转换为目标编码的字节数组后写入响应体 var contentBytes = targetEncoding.GetBytes("abc æøå ÆØÅ"); await Response.Body.WriteAsync(contentBytes); await Response.CompleteAsync(); }
全局配置解决方案
若多个接口需要适配Excel QueryTable,可在Program.cs中全局配置text/plain类型的默认输出编码:
var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(options => { // 找到处理text/plain的字符串输出格式化器 var plainTextFormatter = options.OutputFormatters .OfType<StringOutputFormatter>() .First(f => f.SupportedMediaTypes.Contains("text/plain")); // 添加Windows-1252编码作为支持的输出编码 plainTextFormatter.SupportedEncodings.Add(Encoding.GetEncoding(1252)); }); var app = builder.Build(); app.UseRouting(); app.MapControllers(); app.Run();
注意:如果你的系统默认ANSI编码非Windows-1252,可替换为
Encoding.Default获取系统默认编码,但显式指定Windows-1252更适配丹麦语字符场景。
内容的提问来源于stack exchange,提问作者Klaus Stabil-IT
相关产品推荐
相关产品推荐

